具有不同名称空间的XML向下钻取到所需值

问题描述 投票:-1回答:2

我试图弄清楚如何从以下XML文件获取jxdm:ID的值:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<Abcd:StoreDataSection>
    <Abcd:DataSection>
        <Abcd:FirstStore>
            <box-1:Response>
                <box-1:DataSection>
                    <box-1:Release>
                        <box-1:Activity>
                            <bulb:Date>2017-04-29</bulb:Date>
                            <bulb:Store xsi:type="TPIR:Organization">
                                <bulb:StoreID>
                                    <bulb:ID>D79G2102</bulb:ID>
                                </bulb:StoreID>
                            </bulb:Store>
                        </box-1:Activity>
                    </box-1:Release>
                </box-1:DataSection>
            </box-1:Response>
        </Abcd:FirstStore>
    </Abcd:DataSection>
</Abcd:StoreDataSection>

我一直获得“ null”作为节点的值

Node node = (Node) xPath.evaluate(expression, document, XPathConstants.NODE);

错误消息:

应该在'/'或'//'标记之后执行定位步骤。

这是我当前的Java代码:

try {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document document = builder.parse(new File("c:/temp/testingNamespace.xml"));

    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "//Abcd/StoreDataSection/DataSection/FirstStore//box-1/Response/DataSection/Release/Activity//bulb/Store/StoreID/ID";
    Node node = (Node) xPath.evaluate(expression, document, XPathConstants.NODE);

    node.setTextContent("changed ID");

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.transform(new DOMSource(document), new StreamResult(new File("C:/temp/test-updated.xml")));
} catch (Exception e) {
    System.out.println(e.getMessage());
}

如何格式化正确的XPath,以便我获取该值并进行更改?

java xml xpath xml-namespaces
2个回答
0
投票

这里有很多错误:

  • 错误的直接原因是XML组件名称或名称空间前缀(-)中不允许box-1,因此在XPath位置步骤中不允许。

0
投票
这里还有一个问题,除非您从文档中删除了名称空间。
© www.soinside.com 2019 - 2024. All rights reserved.