简体   繁体   English

XPath解析xml时遇到问题

[英]facing issue while parsing xml with xpath compile

I have just started learning xml parsing through java. 我刚刚开始通过Java学习xml解析。 I am stuck with the below issue for a quite some time now and need some help. 我在以下问题上停留了很长时间,并且需要一些帮助。

I have an xml document which look something like this(just the small representation of a big xml document). 我有一个看起来像这样的xml文档(只是大xml文档的小表示)。

`<shipto>
    <name>Ola Nordmann</name>
    <address>Langgt 23</address>
    <city>4000 Stavanger</city>
    <country>Norway</country>
  </shipto>
  <item id="2">
    <title>Empire Burlesque</title>
    <note>Special Edition</note>
    <quantity>1</quantity>
    <price>10.90</price>
  </item>
  <item>
    <title>Hide your heart</title>
    <quantity>1</quantity>
    <price>9.90</price>
  </item>`

I am trying to find payload when attribute 'id="2"'present. 我正在尝试在属性'id =“ 2”'存在时找到有效载荷。

Below is the regex I am using with xpath compile: 下面是我使用xpath编译的正则表达式:

XPathExpression expr = xpath.compile("//*[@id=\\"2\\"]"); XPathExpression expr = xpath.compile(“ // * [@ id = \\” 2 \\“]”);

The issue: This regular expression gives me 问题:这个正则表达式给了我

`<item id="2">
    <title>Empire Burlesque</title>
    <note>Special Edition</note>
    <quantity>1</quantity>
    <price>10.90</price>
  </item>`

When I only need : 当我只需要:

<title>Empire Burlesque</title> <note>Special Edition</note> <quantity>1</quantity> <price>10.90</price>

How do I achieve this result? 如何取得这个结果?

This question can be really silly as I am just trying to learn xml parsing in java. 这个问题真的很愚蠢,因为我只是想学习Java中的xml解析。 Please help and thank you in advance. 请帮助并提前感谢您。

Use this line to get only the subnodes: 使用此行仅获取子节点:

XPathExpression expr = xpath.compile("//*[@id=\"2\"]/*");

Result: 结果:

<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>

This expression returns all children of all <item> elements with the attribute value @id = 2 . 此表达式返回属性值@id = 2的所有<item>元素的所有子元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM