问题
I am trying to retrieve the value of a child node of a given node on a Windows Machine. Suppose I have the following XML structure:
<xsd:type name="type1">
<xsd:example>
<xsd:description>This is the description of said type1 tag</xsd:description>
</xsd:example>
</xsd:type>
I'd like to retrieve the value in between the xsd:description tag given that it is the child of the xsd:type tag with the name="type1" attribute. In other words, I'd like to retrieve "This is the description of said type1 tag".
On a Mac, I'm able to run the below command to retrieve just that with the following:
xml sel -t -v "//xsd:type[@name=\"type1\"]" -n filePath.xml
Which then returns: "This is the description of said type1 tag" as expected.
However, when I run the exact same command on my Windows machine, the command returns an empty string. I'm not sure what the differences are between Mac and Windows, but I can't seem to figure out the equivalent Windows command.
回答1:
This is most likely to be related to not properly defining a namespace.
XML Starlet provides a -N option which is described as:
-N <name>=<value> - predefine namespaces (name without 'xmlns:') ex: xsql=urn:oracle-xsql
Change your command to the following instead:
xml sel -N xsd="http://www.w3.org/2001/XMLSchema" -t -v "//xsd:type[@name=\"type1\"]//xsd:description/text()" -n filePath.xml
Notes:
The part below was added to predefine the namespace for the XPath expression, so that it addresses the elements in the correct namespace:
-N xsd="http://www.w3.org/2001/XMLSchema"
Also the XPath expression was changed to the following to better address your actual requirement:
"//xsd:type[@name=\"type1\"]//xsd:description/text()"
This expression matches the
text()
node of anyxsd:description
element node that is a descendant of anyxsd:type
element node which has aname="type1"
attribute.
来源:https://stackoverflow.com/questions/58693553/retrieve-value-of-child-node-given-attribute