2012-10-22 42 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 –