首页 文章

用于获取子属性值的XPath表达式

提问于
浏览
0

我试图从示例XML文件中获取子属性的值:

<book id="123">
<title>Game of Thrones</title>
<season>5</season>
</book>

我的XPath表达式是 /book ,但有了这个,我只能获得 id 的值 .

如果我的XML是这样的:

<book> 
   <id>123</id>
   <title>Game of Thrones</title>
   <season>5</season>
</book>

...如果我将表达式设为 /book ,我没有得到任何值 .

预期结果:

123
Game of Thrones
5

3 回答

  • 0

    给出像这样的Xml

    <books>
      <book>
        <id>123</id>
        <title>Game of Thrones</title>
        <season>5</season>
      </book>
      <book>
        <id>124</id>
        <title>Harry Potter</title>
        <season>5</season>
      </book>
    </books>
    

    此Xpath将检索给定id的元素

    / books / book [id = 124]

  • 0

    如果您的XML文档确实如此

    <book> 
       <id>123</id>
       <title>Game of Thrones</title>
       <season>5</season>
    </book>
    

    而你确实希望结果

    123
    Game of Thrones
    5
    

    然后,您正在查找输入文档中存在的文本节点 . 选择文档中所有文本节点的XPath表达式是

    //text()
    

    这也将选择仅包含空格的文本节点,因此结果可能看起来像(单个结果由 ------- 分隔):

    -----------------------
    123
    -----------------------
    -----------------------
    Game of Thrones
    -----------------------
    -----------------------
    5
    -----------------------
    

    如您所见,结果中只有空白行,但确切的行为取决于您的XPath引擎以及如何显示结果 .


    如果应排除仅限换行符,请使用谓词:

    //text()[normalize-space()]
    

    这种技术解释为here . 基本上,如果在规范化空格后留下文本内容,则谓词返回True .

  • 0

    对于在问题中指定为第二个示例的xml,您可以使用此XPath表达式获取所有子元素值:

    /book[id=123]/child::*/text()
    

    实际上, /book[id=123] 选择具有id = 123的 <book> 元素, child::* 获取其子项, text() 从子项中获取文本 .

相关问题