gpt4 book ai didi

java - 如何使用 Xpath 解析复杂的 XML

转载 作者:行者123 更新时间:2023-11-30 02:26:31 24 4
gpt4 key购买 nike

我有一个 XML 如下:

<Service xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="someurl" xsi:schemaLocation="someurl Sample.xsd">
<RequestControl>
<requestID>100129</requestID>
<Control>
<requesterName>Admin</requesterName>
<requesterLanguage>100</requesterLanguage>
</Control>
</RequestControl>
<Inquiry>
<InquiryType>getParty</InquiryType>
<InquiryParam>
<Param name="PartyId">854850029276139020</Param>
</InquiryParam>
</Inquiry>
</Service>

我想使用 XPath XML 解析器从标记中提取值“getParty”。我使用以下作为我的表达:

expression = xPath.compile("/Service/Inquiry/InquiryType/text()");

如何为上述内容编写准确且完整的java代码?我只想提取 <InquiryType>getParty</InquiryType> 的值.

最佳答案

尝试你的代码,看起来对我来说工作得很好。这是我所做的

public static void main(String ... args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(System.getProperty("user.dir") + "/src/main/resources/test.xml");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expression = xpath.compile("/Service/Inquiry/InquiryType/text()");
NodeList xpathNodeList = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);
System.out.println("InquiryType is : " +xpathNodeList.item(0));
}

test.xml 包含您正在使用的 xml

<Service xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="someurl" xsi:schemaLocation="someurl Sample.xsd">
<RequestControl>
<requestID>100129</requestID>
<Control>
<requesterName>Admin</requesterName>
<requesterLanguage>100</requesterLanguage>
</Control>
</RequestControl>
<Inquiry>
<InquiryType>getParty</InquiryType>
<InquiryParam>
<Param name="PartyId">854850029276139020</Param>
</InquiryParam>
</Inquiry>
</Service>

关于java - 如何使用 Xpath 解析复杂的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com