繁体   English   中英

使用dom4j在xml文档上添加元素

[英]Add element on xml document with dom4j

我目前正在开发对SOAP Web服务的调用,我需要能够动态地在XML文档中添加元素。 我尝试为此使用dom4j库,该库在其他情况下效果很好,但是我无法使用当前的XML文档来实现。

我的目标是在<urn:sObjects>节点下添加一些<fieldsToNull>fieldname</fieldsToNull>元素。 这样说似乎很简单,但我想我在使用XML时遇到问题

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com" xmlns:urn1="urn:sobject.enterprise.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
    <urn:SessionHeader>
    <urn:sessionId>sessionId</urn:sessionId>
    </urn:SessionHeader><urn:AssignmentRuleHeader>
    <urn:assignmentRuleId/><urn:useDefaultRule>1</urn:useDefaultRule></urn:AssignmentRuleHeader>
</soapenv:Header>
<soapenv:Body>
    <urn:update>
        <urn:sObjects>
            <type>Account</type>
            <Id/>
            <Name/>
        </urn:sObjects>
    </urn:update>
</soapenv:Body>

这是我根据某些主题的答案做出的最后一次尝试。 它不会产生错误,但是不起作用:

org.dom4j.Document msgDocument = ((routines.system.Document)input_row.Body).getDocument();
org.dom4j.Element root = msgDocument.getRootElement();
String xpathExpression = "Enveloppe.Body.update.Objects";
List<Node> nodes = root.selectNodes(xpathExpression);

for (Node node : nodes) {
    Element e = (Element) node;
    e.addElement("fieldsToNull").addText("Name");
}

routines.system.Document newMsgDocument = new routines.system.Document();
newMsgDocument.setDocument(msgDocument);
output_row.Body = newMsgDocument;

有人能给我一个提示吗?

精度:我的代码将在Talend工作中设置。 它不会改变其工作方式,而只是说出来。

经过更多调查,我终于可以使用以下代码来完成我想要的工作:

org.dom4j.Document msgDocument = ((routines.system.Document)input_row.Body).getDocument();

Map uris = new HashMap();
uris.put("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
uris.put("urn", "urn:partner.soap.sforce.com");

XPath xpath = msgDocument.createXPath("//soapenv:Body/urn:update/urn:sObjects");
xpath.setNamespaceURIs(uris);
List<Node> nodes = xpath.selectNodes(msgDocument);

for (Node node : nodes) {
    Element e = (Element) node;
    Element fieldsToNull = e.addElement("fieldsToNull");
    fieldsToNull.setText("Name");
    System.out.println(fieldsToNull.toString());
}

routines.system.Document newMsgDocument = new routines.system.Document();
newMsgDocument.setDocument(msgDocument);
output_row.Body = newMsgDocument;

暂无
暂无

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

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