XPath 搜索“id”属性,给出 NPE - Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22556423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:28:27  来源:igfitidea点击:

XPath search by "id" attribute , giving NPE - Java

javaxmlxpath

提问by tomaytotomato

All,

全部,

I have multiple XML templates that I need to fill with data, to allow my document builder class to use multiple templates and insert data correctly

我有多个 XML 模板需要填充数据,以允许我的文档构建器类使用多个模板并正确插入数据

I designate the node that I want my class to insert data to by adding an attribute of:

我通过添加以下属性来指定我希望我的类向其中插入数据的节点:

id="root"

身=“根”

One example of an XML

XML 的一个示例

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<SiebelMessage MessageId="07f33fa0-2045-46fd-b88b-5634a3de9a0b" MessageType="Integration Object" IntObjectName="" IntObjectFormat="Siebel Hierarchical" ReturnCode="0" ErrorMessage="">
    <listOfReadAudit >
        <readAudit id="root">
            <recordId mapping="Record ID"></recordId>
            <userId mapping="User ID"></userId>
            <customerId mapping="Customer ID"></customerId>
            <lastUpd mapping="Last Updated"></lastUpd>
            <lastUpdBy mapping="Last Updated By"></lastUpdBy>
            <busComp mapping="Entity Name"></busComp>
        </readAudit>
    </listOfReadAudit>
</SiebelMessage>

Code

代码

expr = xpath.compile("//SiebelMessage[@id='root']");
root = (Element) expr.evaluate(xmlDoc, XPathConstants.NODE);
Element temp = (Element) root.cloneNode(true);

Using this example: XPath to select Element by attribute value

使用此示例: XPath 按属性值选择元素

The expression is not working:

表达式不起作用:

//SiebelMessage[@id='root']

//SiebelMessage[@id='root']

Any ideas what I am doing wrong?

任何想法我做错了什么?

采纳答案by Stefan Pries

Try this:

尝试这个:

//readAudit[@id='root']

This selects all readAuditelements with the idattribute set to root(it should be just 1 element in your case).

这将选择属性设置为的所有readAudit元素(在您的情况下应该只有 1 个元素)。idroot

You could make sure it returns maximum 1 element with this:

您可以确保它返回最多 1 个元素:

//readAudit[@id='root'][1]

回答by kutschkem

What you are doing is selecting SiebelMessage nodes with the attribute id='root'.

您正在做的是选择具有属性 id='root' 的 SiebelMessage 节点。

But the SiebelMessage doesn't have an id, it's the readAudit you are after. So either do

但是 SiebelMessage 没有 id,它是您所追求的 readAudit。所以要么做

//readAudit[id='root']

or

或者

//SiebelMessage//readAudit[id='root']