简体   繁体   English

使用简单XML和xpath解析XML文件

[英]Parse XML file with Simple XML and xpath

I'm trying to obtain the values of the nodes "/entry/comment[type="subcellular location"]/subcellularLocation/location" from this file http://www.uniprot.org/uniprot/P12345.xml 我正在尝试从此文件http://www.uniprot.org/uniprot/P12345.xml获取节点“ / entry / comment [type =“ subcellular location”] / subcellularLocation / location”的值

I'm using SimpleXML and xpath but I can't access to this nodes with: 我正在使用SimpleXML和xpath,但无法通过以下方式访问此节点:

$var = "http://www.uniprot.org/uniprot/P12345.xml";
$Unip_result= new SimpleXMLElement($var, NULL, TRUE);

$value=$Unip_result->xpath("/entry/comment[@type='subcellular location']");

The result is an empty array... 结果是一个空数组...

The XML has namespaces, you need to register a prefix for it and use the prefix in the XPath expression. XML具有名称空间,您需要为其注册一个前缀并在XPath表达式中使用该前缀。 Check SimpleXMLElement::registerXpathNamespace() . 检查SimpleXMLElement::registerXpathNamespace()

Your XML has default namespace (the one without prefix : xmlns="...." ). 您的XML具有默认的名称空间(不带前缀的名称空间: xmlns="...." )。 The element where the default namespace declared and all of it's descendant without prefix and without different default namespace are considered in the ancestor's default namespace. 祖先的默认名称空间中考虑了声明了默认名称空间的元素及其所有后代(不带前缀且没有其他默认名称空间)。 So, you need to register a prefix that point to default namespace URI and use that prefix in the XPath : 因此,您需要注册一个指向默认名称空间URI的前缀,并在XPath中使用该前缀:

$var = "http://www.uniprot.org/uniprot/P12345.xml";
$Unip_result = new SimpleXMLElement($var, NULL, TRUE);
$Unip_result->registerXPathNamespace('ns', 'http://uniprot.org/uniprot');

$value = $Unip_result->xpath("/ns:uniprot/ns:entry/ns:comment[@type='subcellular location']");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM