ChatGPT解决这个技术问题 Extra ChatGPT

通过 XPath 提取属性节点的值

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

它只返回 child 元素,但我想要 name 属性的值。

对于我的示例 XML 文件,我希望输出如下:

Child_2
Child_4
Child_1
Child_3
Getting attribute using XPath 的可能重复项

R
Rory O'Kane
//Parent[@id='1']/Children/child/@name 

您原来的 child[@name] 是指具有属性 name 的元素 child。你想要child/@name


我同意,问题是如何获取属性的值
如果我只想提取标签之间存在的值/描述/数据怎么办......
F
Flow

要仅获取值(没有属性名称),请使用 string()

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

fn:string() 函数将其参数的值作为 xs:string 返回。如果它的参数是一个属性,它将因此返回属性的值作为 xs:string


对于 xqilla,必须调用 xs:string。我想知道为什么。
@krlmlr 可能 xs 是 XPath 函数的命名空间前缀。所以他们不会和其他人混在一起。
哈哈。这是唯一真正回答问题的答案。 +1
这将只提供 xmllint 中的第一个命中
如果我有一个属性列表并且我需要它们的值怎么办? string() 似乎只返回第一个值。
a
abatishchev

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

属性无法序列化,因此您无法以 xml 外观结果返回它们。您需要做的是使用 data() 函数从属性中获取数据。


属性上的 data() 函数在 xmllint 中给出错误“XPath 错误:无效表达式”。
V
Vinod Srivastav

如上回答:

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

将仅输出属于其谓词 [@id=1] 指定的 Parent 的 4 个 child 节点的 name 属性。然后,您需要将谓词更改为 [@id=2] 以获取下一个 Parentchild 节点集。

但是,如果您完全忽略 Parent 节点并使用:

//child/@name

您可以一次性选择所有 child 个节点的 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"

S
Soner Gönül
//Parent/Children[@  Attribute='value']/@Attribute

这种情况可以在元素具有 2 个属性的情况下使用,我们可以在另一个属性的帮助下获得一个属性。


E
Ed Bangga

对于所有带有命名空间的 xml,使用 local-name()

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

a
abatishchev

@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

佚名

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

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

在您的情况下,这是将返回的 xpath

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

它将返回:

Child_2
Child_4
Child_1
Child_3