2012-10-22 122 views
1

我有一个用PHP SimpleXML解析的XML。我的XML文件的某些部分是这样的:用PHP解析XML - SimpleXML

<deviceStatusPolling interval="60"> 
    <r:datapoint programmaticName="t_val_sys_pct_mssDbPartitionUsage" /> 
</deviceStatusPolling> 

当我分析它,这就是我得到:

Parsing 'deviceStatusPolling'... 
    Has 1 attribute(s): 
    - interval: 60 

它不解析孩子:

<r: datapoint programmaticName="t_val_sys_pct_mssDbPartitionUsage" /> 

这是解析功能:

function parse_recursive(SimpleXMLElement $element, $level = 0) { 
$indent = str_repeat("\t", $level); // determine how much we'll indent 

$value = trim((string) $element); // get the value and trim any whitespace from the start and end 
$attributes = $element->attributes(); // get all attributes 
$children = $element->children();  // get all children 

echo "{$indent}Parsing '{$element->getName()}'...<br>"; 
if(count($children) == 0 && !empty($value)) // only show value if there is any and if there aren't any children 
{ 
    echo "{$indent}Value: {$element}<br>"; 
} 

// only show attributes if there are any 
if(count($attributes) > 0) 
{ 
    echo $indent.'Has '.count($attributes).' attribute(s):<br>'; 
    foreach($attributes as $attribute) 
    { 
     echo "{$indent}- {$attribute->getName()}: {$attribute}<br>"; 
    } 
} 

// only show children if there are any 
if(count($children)) 
{ 
    echo $indent.'Has '.count($children).' child(ren):<br>'; 
    foreach($children as $child) 
    { 
     parse_recursive($child, $level+1); // recursion :) 
    } 
} 

echo $indent; // just to make it "cleaner" 
echo "<br>"; 
} 

它是SimpleXML的限制吗?或者我做错了什么?

问候

+2

欢迎来到SO!向我们展示您的代码/您的打印方式。 – nickhar

+0

也请告诉我们您期望从印刷中得到什么。 – Serge

+0

我们仍然看不到你在做什么来打印它 - 什么代码?打印? – nickhar

回答

0

你的问题不是很清楚,但可能需要的东西是这样的:

$xmlDoc = new SimpleXMLElement($docStr); 
$allNamespaces = $xmlDoc->getNamespaces(true); 
foreach ($allNamespaces as $nspace => $nurl) { 
     $xmlDoc->registerXPathNamespace($nspace, $nurl); 
} 

阅读上的SimpleXML和命名空间。

这几乎肯定是您的问题的解决方案。请看这里: http://blog.sherifmansour.com/?p=302

+0

我试过了,但它没有解决我的问题。 – alereis

+0

添加了其他信息:http://blog.sherifmansour.com/?p = 302 –