且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中的 XML 中的现有节点下添加新节点

更新时间:2022-05-23 06:33:25

这应该可以解决问题.从我的头顶写的,未经测试.我已经知道它只适用于没有命名空间的情况.因此,您可以首先通过从文档中剥离名称空间来验证它是否有效.然后再次添加它们,修改代码使其匹配.

This should do the trick. Written from the top of my head and untested. I already know it only applies without namespace. So you can verify that it works first by stripping off the namespaces from your document. Then add them again, modifying the code so that it matches.

Document document = getXmlAsDocument(updatedXMLPath);
XPath xpath = XPathFactory.newInstance().newXPath();
Element restSchema = (Element)xpath.evaluate("/TrustFrameworkPolicy/BuildModel/RestSchema", document, XPathConstants.NODE);

Element dataType = document.createElement("DataType");
dataType.appendChild(document.createText("string");
Element custType = document.createElement("CustType");
custType.setAttribute("Id", "regular.Command-Nest.type1");
custType.appendChild(dataType);
restSchema.appendChild(custType);

// finally serialize using the identity transformer

对于命名空间,您必须进行两项更改:

For namespaces you have to make two changes:

  • 不要使用 createElement,而是使用 createElementNS
  • 您需要使用命名空间前缀并为 xpath 引擎提供 NamespaceContext,而不是使用我使用的简单 xpath.