如何通过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

//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

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

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

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

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

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

你应该使用//Parent[@id='1']/Children/child/data(@name)

属性不能被序列化,所以不能在xml格式的结果中返回它们。您需要做的是使用data()函数从属性中获取数据。

如上所述:

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

将只输出4个子节点的name属性,这些子节点属于谓词[@id=1]指定的父节点。然后需要将谓词更改为[@id=2],以获得下一个Parent的子节点集。

然而,如果你完全忽略父节点并使用:

//child/@name

您可以一次选择所有子节点的name属性。

name="Child_2"
name="Child_4"
name="Child_1"
name="Child_3"
name="Child_1"
name="Child_2"
name="Child_4"
name="Child_3"

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

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

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

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

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

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

它将返回:

Child_2
Child_4
Child_1
Child_3