Extract value of attribute node via XPath

后端 未结 7 1033
醉酒成梦
醉酒成梦 2020-11-28 01:59

How can I extract the value of an attribute node via XPath?

A sample XML file is:


  

        
相关标签:
7条回答
  • 2020-11-28 02:06
    //Parent/Children[@  Attribute='value']/@Attribute
    

    This is the case which can be used where element is having 2 attribute and we can get the one attribute with the help of another one.

    0 讨论(0)
  • 2020-11-28 02:07

    You should use //Parent[@id='1']/Children/child/data(@name)

    The attributes can not be serialized so you can't return them in an xml looking result. What you need to do is obtain the data from the attribute using data() function.

    0 讨论(0)
  • 2020-11-28 02:08

    for all xml with namespace use local-name()

    //*[local-name()='Parent'][@id='1']/*[local-name()='Children']/*[local-name()='child']/@name 
    
    0 讨论(0)
  • 2020-11-28 02:18

    As answered above:

    //Parent[@id='1']/Children/child/@name 
    

    will only output the name attribute of the 4 child nodes belonging to the Parent specified by its predicate [@id=1]. You'll then need to change the predicate to [@id=2] to get the set of child nodes for the next Parent.

    However, if you ignore the Parent node altogether and use:

    //child/@name
    

    you can select name attribute of all child nodes in one go.

    name="Child_2"
    name="Child_4"
    name="Child_1"
    name="Child_3"
    name="Child_1"
    name="Child_2"
    name="Child_4"
    name="Child_3"
    
    0 讨论(0)
  • 2020-11-28 02:27

    @ryenus, You need to loop through the result. This is how I'd do it in vbscript;

    Set xmlDoc = CreateObject("Msxml2.DOMDocument")
    xmlDoc.setProperty "SelectionLanguage", "XPath"
    xmlDoc.load("kids.xml")
    
    'Remove the id=1 attribute on Parent to return all child names for all Parent nodes
    For Each c In xmlDoc.selectNodes ("//Parent[@id='1']/Children/child/@name")
        Wscript.Echo c.text
    Next
    
    0 讨论(0)
  • 2020-11-28 02:33
    //Parent[@id='1']/Children/child/@name 
    

    Your original child[@name] means an element child which has an attribute name. You want child/@name.

    0 讨论(0)
提交回复
热议问题