Retrieve value of child node given attribute

杀马特。学长 韩版系。学妹 提交于 2020-01-25 06:17:55

问题


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:

  1. 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"

  2. 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 any xsd:description element node that is a descendant of any xsd:type element node which has a name="type1" attribute.



来源:https://stackoverflow.com/questions/58693553/retrieve-value-of-child-node-given-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!