duangaixing1509 2016-06-24 21:31
浏览 60
已采纳

使用命名空间读取XML文件

I need som help reading a XML that has namespaces. I can read file with out any namepaces but not with namespaces..

XML sample:

<?xml version="1.0" encoding="utf-8"?>
<OrderResponse xmlns:cac="urn:basic:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:xsi="http://www.w3.org/" xmlns:cbc="urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2" xmlns="urn:basic:names:specification:ubl:schema:xsd:OrderResponse-2">
  <cbc:UBLVersionID>2.1</cbc:UBLVersionID>
  <cbc:AccountingCostCode>TESTER TEST</cbc:AccountingCostCode>
  <cac:OrderReference>
    <cbc:ID>100067010</cbc:ID>
    <cbc:IssueDate>2016-06-15</cbc:IssueDate>
    <cbc:OrderTypeCode>EDI</cbc:OrderTypeCode>
  </cac:OrderReference>
</OrderResponse>

I need to get the value of the .. Im trying do it with DomDocument. Here is my code:

function SearchXMLID($xml){
var_dump($xml);
$doc = new DOMDocument();
$doc->load($xml);
$id = $doc->getElementsByTagNameNS('urn:basic:names:specification:ubl:schema:xsd:CommonAggregateComponents-2','cbc:ID');

  foreach($id as $i){
    echo "<pre>";var_dump('NS',$i->nodeValue,PHP_EOL);"</pre>";

  }
}

$files = glob('dataXMl/*xml');
echo "<pre>";var_dump($files,PHP_EOL);"</pre>";

foreach($files as $f){
    SearchXMLID($f);
 }

This code works but is getting all namespaces with 'cbc:' and stores the in a string..

    array(1) {
  [0]=>
  string(17) "dataXMl/test1.xml"
}
string(1) "
"
string(17) "dataXMl/test1.xml"
string(2) "NS"
string(40) "
    100000050
    2016-06-15
    EDI
  "
string(1) "
"

It gets all tags with the namespace 'cbc'.. but i want to get the tag 'cbc:ID' only.

What am i doing wrong?

</div>
  • 写回答

1条回答 默认 最新

  • douyan8070 2016-06-24 22:39
    关注

    I'm no expert with php coding but my gut tells me that both of your parameters for getElementsByTagNameNS are wrong.

    Try this:

    $id = $doc->getElementsByTagNameNS('urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2','ID');
    

    i.e.

    use the correct namespace-uri: "urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2" and drop the cbc prefix
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器