使用属性从复杂的XML获取所有叶子 [英] Get all leaf from complex XML with attributes
问题描述
我有那种XML文件
myxml.xml
myxml.xml
<?xml version="1.0" encoding="utf-8"?>
<products nb="2" type="new">
<product ean="12345677654321">
<sku>Product1</sku>
<parameters>
<short_desc> Short description of the product1 </short_desc>
<price currency="USD">19.65</price>
</parameters>
</product>
<product ean="12345644654321">
<sku>Product2</sku>
<parameters>
<long_desc> Long description of the product2 </long_desc>
<price currency="USD">19.65</price>
<vat>20</vat>
</parameters>
</product>
</products>
我要这样一个数组
/products/@nb
/products/@type
/products/product/@ean
/products/product/sku
/products/product/parameters/short_desc
/products/product/parameters/long_desc
/products/product/parameters/price
/products/product/parameters/price/@currency
/products/product/parameters/vat
使用此代码我几乎得到了这个结果
I almost this result with this code
getpath.xsl
getpath.xsl
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vApos">'</xsl:variable>
<xsl:template match="*[@* or not(*)] ">
<xsl:if test="not(*)">
<xsl:apply-templates select="ancestor-or-self::*" mode="path"/>
<xsl:text>
</xsl:text>
</xsl:if>
<xsl:apply-templates select="@*|*"/>
</xsl:template>
<xsl:template match="*" mode="path">
<xsl:value-of select="concat('/',name())"/>
<xsl:variable name="vnumPrecSiblings" select=
"count(preceding-sibling::*[name()=name(current())])"/>
<xsl:if test="$vnumPrecSiblings">
<xsl:value-of select="concat('[', $vnumPrecSiblings +1, ']')"/>
</xsl:if>
</xsl:template>
<xsl:template match="@*">
<xsl:apply-templates select="../ancestor-or-self::*" mode="path"/>
<xsl:value-of select="concat('/@',name())"/>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
$xslDoc = new \DOMDocument();
$xslDoc->substituteEntities = true;
$xslDoc->load('getpath.xsl');
$xmlDoc = new \DOMDocument();
$xmlDoc->load('myxml.xml');
$proc = new \XSLTProcessor();
$proc->importStylesheet($xslDoc);
$rest = $proc->transformToXML($xmlDoc);
$res = preg_replace("/\\s/"," ", $rest);
$path = explode(" ", $res);
foreach ($path as $key => $value) {
if(!empty($value) && !preg_match("/\[.*\]/", $value))
$fields[] = $value;
}
return $fields;
这段代码给我
/products/@nb
/products/@type
/products/product/@ean
/products/product/sku
/products/product/parameters/short_desc
/products/product/parameters/price
/products/product/parameters/price/@currency
/ products / product / parameters / long_desc和/ products / product / parameters / price / vat缺失:(
/products/product/parameters/long_desc and /products/product/parameters/price/vat are missing :(
我用xslt解析了完整的XML还是在没有XSLT的情况下解决了这个问题?
How can I parse the full XML with xslt ? Or have you a solution without XSLT ???
推荐答案
是的,您可以使用一些方法
Yeah you can do it with some Xpath in PHP.
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
function getNodeExpression(DOMNode $node, array &$namespaces) {
$name = $node->localName;
$namespace = $node->namespaceURI;
if ($namespace == '') {
return ($node instanceOf DOMAttr ? '@' : '').$name;
} elseif (isset($namespaces[$namespace])) {
$prefix = $namespaces[$namespace];
} else {
$xmlns = $prefix = ($node->prefix == '') ? 'ns' : $node->prefix;
$i = 1;
while (in_array($xmlns, $namespaces)) {
$xmlns = $prefix.'-'.$i;
$i++;
}
$namespaces[$namespace] = $prefix;
}
return ($node instanceOf DOMAttr ? '@' : '').$prefix.':'.$name;
}
$result = [];
$namespaces= [];
foreach ($xpath->evaluate('//*[count(*) = 0]|//@*') as $node) {
$path = '';
foreach ($xpath->evaluate('ancestor::*', $node) as $parent) {
$path = '/'.getNodeExpression($parent, $namespaces);
}
$path .= '/'.getNodeExpression($node, $namespaces);
$result[$path] = TRUE;
}
array(10) {
[0]=>
string(13) "/products/@nb"
[1]=>
string(15) "/products/@type"
[2]=>
string(13) "/product/@ean"
[3]=>
string(12) "/product/sku"
[4]=>
string(22) "/parameters/short_desc"
[5]=>
string(17) "/parameters/price"
[6]=>
string(16) "/price/@currency"
[7]=>
string(21) "/parameters/long_desc"
[8]=>
string(20) "/long_desc/@xml:lang"
[9]=>
string(15) "/parameters/vat"
}
array(1) {
["http://www.w3.org/XML/1998/namespace"]=>
string(3) "xml"
}
此处的复杂部分是解析名称空间并为其生成前缀。因此,让我们详细看一下:
The complex part at this is to resolve the namespaces and generate prefixes for them. So let's take a detailed look:
获取本地名称(没有名称空间前缀的标签名称)和名称空间。
Get the local name (tag name without namespace prefix) and the namespace.
$name = $node->localName;
$namespace = $node->namespaceURI;
如果命名空间为空,则不需要任何前缀,而仅返回节点名称的表达式。 / p>
If the namespace is empty we do not need any prefix return an expression with just the node name.
if ($namespace == '') {
return ($node instanceOf DOMAttr ? '@' : '').$name;
否则,检查名称空间是否已在另一个节点上使用并重用该前缀。
Otherwise check if the namespace was already used on another node and reuse that prefix.
} elseif (isset($namespaces[$namespace])) {
$prefix = $namespaces[$namespace];
如果这是未知的名称空间,请读取此节点上使用的前缀。如果节点未使用前缀,则使用字符串 ns。
If here is an unknown namespace, read the prefix used on this node. If the node didn't use a prefix use the string "ns".
} else {
$xmlns = $prefix = ($node->prefix == '') ? 'ns' : $node->prefix;
验证前缀是否尚未用于另一个命名空间,请添加一个数字并增加它,直到我们有一个
Validate that the prefix is not already used for another namespace add a number and increase it until we have an unique prefix.
$i = 1;
while (in_array($xmlns, $namespaces)) {
$xmlns = $prefix.'-'.$i;
$i++;
}
存储名称空间=>下一个调用的前缀定义。
Store the namespace => prefix definition for the next call.
$namespaces[$namespace] = $prefix;
返回包含前缀的表达式。
Return an expression including the prefix.
return ($node instanceOf DOMAttr ? '@' : '').$prefix.':'.$name;
命名空间数组可用于在Xpath对象上注册所有需要的命名空间前缀。
The namespace array can be used to register all needed namespace prefix on an Xpath object.
这篇关于使用属性从复杂的XML获取所有叶子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!