我有一个XmlDocument用Weblogic XmlDocument解析器创建的 java 。
我想XMLDocument用我自己的数据替换这个标签的内容,或者如果它不存在就插入标签。
<customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
Run Code Online (Sandbox Code Playgroud)
例如,我想在位置标签中插入一个 URL:
<location>http://something</location>
Run Code Online (Sandbox Code Playgroud)
但否则保留 XML 原样。
目前我使用XMLCursor:
XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
Run Code Online (Sandbox Code Playgroud)
我试图找到一种“快速”的xquery方法来做到这一点,因为它XmlDocument有一个execQuery方法,但并没有发现它很容易。
有没有人有比这更好的方法?好像有点讲究。
基于 XPath 的方法怎么样?我喜欢这种方法,因为逻辑非常容易理解。代码几乎是自我记录的。
如果您的 xml 文档可用作 org.w3c.dom.Document 对象(大多数解析器返回),那么您可以执行以下操作:
// get the list of customdata nodes
NodeList customDataNodeSet = findNodes(document, "//customdata" );
for (int i=0 ; i < customDataNodeSet.getLength() ; i++) {
Node customDataNode = customDataNodeSet.item( i );
// get the location nodes (if any) within this one customdata node
NodeList locationNodeSet = findNodes(customDataNode, "location" );
if (locationNodeSet.getLength() > 0) {
// replace
locationNodeSet.item( 0 ).setTextContent( "http://stackoverflow.com/" );
}
else {
// insert
Element newLocationNode = document.createElement( "location" );
newLocationNode.setTextContent("http://stackoverflow.com/" );
customDataNode.appendChild( newLocationNode );
}
}
Run Code Online (Sandbox Code Playgroud)
这是执行 XPath 搜索的辅助方法 findNodes。
private NodeList findNodes( Object obj, String xPathString )
throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile( xPathString );
return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5063 次 |
| 最近记录: |