如何通过XPath提取属性节点的值?

一个示例XML文件是:

<parents name='Parents'>
  <Parent id='1' name='Parent_1'>
    <Children name='Children'>
      <child name='Child_2' id='2'>child2_Parent_1</child>
      <child name='Child_4' id='4'>child4_Parent_1</child>
      <child name='Child_1' id='3'>child1_Parent_1</child>
      <child name='Child_3' id='1'>child3_Parent_1</child>
    </Children>
  </Parent>
  <Parent id='2' name='Parent_2'>
    <Children name='Children'>
      <child name='Child_1' id='8'>child1_parent2</child>
      <child name='Child_2' id='7'>child2_parent2</child>
      <child name='Child_4' id='6'>child4_parent2</child>
      <child name='Child_3' id='5'>child3_parent2</child>
    </Children>
  </Parent>
</parents>

到目前为止,我有这个XPath字符串:

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

它只返回子元素,但我希望有name属性的值。

对于我的示例XML文件,下面是我希望输出的内容:

Child_2
Child_4
Child_1
Child_3

当前回答

下面是使用XPath-提取属性值和文本值的标准公式

为Web元素提取属性值 elementXPath / @attributeName 为Web Element-提取文本值 elementXPath / text ()

在你的例子中,这里是返回的xpath

//parent[@name='Parent_1']//child/@name

它将返回:

Child_2
Child_4
Child_1
Child_3

其他回答

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

您的原始子元素[@name]表示具有属性名称的子元素。你想要child/@name。

@ryenus,你需要遍历结果。这是我在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

对于所有带有名称空间的XML使用local-name()

//*[local-name()='Parent'][@id='1']/*[local-name()='Children']/*[local-name()='child']/@name 

如果只得到值(没有属性名),使用string():

字符串(父[@ id = ' 1 '] / / /孩子/孩子/ @ name)

fn:string()函数将其参数的值返回为xs:string。如果它的参数是一个属性,那么它将以xs:string的形式返回属性值。

//Parent/Children[@  Attribute='value']/@Attribute

这种情况下,元素有两个属性,我们可以通过另一个属性获得其中一个属性。