操作/编辑现有 xml 文档的最佳 java Xml 解析器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2523381/
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
best java Xml parser to manipulate/edit an existing xml document
提问by anjanb
TASK : I have an existing xml document (UTF-8) which uses xml namespaces and xml schema. I need to parse to a particular element, append content (that also needs to use xml namespace prefixes) to this element and then write out the Document again.
任务:我有一个现有的 xml 文档 (UTF-8),它使用 xml 命名空间和 xml 架构。我需要解析到一个特定的元素,将内容(也需要使用 xml 命名空间前缀)附加到这个元素,然后再次写出文档。
which is the best XML parser library that I should be using for this TASK ?
哪个是我应该用于此任务的最佳 XML 解析器库?
I've seen a previous thread (Best XML parser for Java) but was not sure if dom4j or JDOM is any good for namespaces/xmlSchema and good support for UTF-8 characters.
我看过以前的线程(Java 的最佳 XML 解析器),但不确定 dom4j 或 JDOM 是否对命名空间/xmlSchema 有任何好处以及对 UTF-8 字符的良好支持。
Some parsers that seems like a task for
JDom
Dom4J
XOM
WoodStock
一些解析器似乎是
JDom
Dom4J
XOM
WoodStock的任务
Any idea which one is the best ? :-) I use JDK 6 and would prefer NOT to use the built-in SAX/DOM facilities to do this job because that requires me to write too much code.
知道哪一个是最好的吗?:-) 我使用 JDK 6 并且不想使用内置的 SAX/DOM 工具来完成这项工作,因为这需要我编写太多的代码。
Would help to have some examples of doing such a task.
将有助于获得一些执行此类任务的示例。
采纳答案by Dean J
Using JDOM, taking an InputStream and making it a Document:
使用 JDOM,获取 InputStream 并将其设为 Document:
InputStream inputStream = (InputStream)httpURLConnection.getContent();
DocumentBuilderFactory docbf = DocumentBuilderFactory.newInstance();
docbf.setNamespaceAware(true);
DocumentBuilder docbuilder = docbf.newDocumentBuilder();
Document document = docbuilder.parse(inputStream, baseUrl);
At that point, you have the XML in a Java object. Done. Easy.
此时,您在 Java 对象中拥有了 XML。完毕。简单。
You can either use the document object and the Java API to just walk through it, or also use XPath, which I find easier (once I learned it).
您可以使用文档对象和 Java API 来浏览它,也可以使用 XPath,我觉得这更容易(一旦我学会了它)。
Build an XPath object, which takes a bit:
构建一个 XPath 对象,这需要一点时间:
public static XPath buildXPath() {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(new AtomNamespaceContext());
return xpath;
}
public class AtomNamespaceContext implements NamespaceContext {
public String getNamespaceURI(String prefix) {
if (prefix == null)
throw new NullPointerException("Null prefix");
else if ("a".equals(prefix))
return "http://www.w3.org/2005/Atom";
else if ("app".equals(prefix))
return "http://www.w3.org/2007/app";
else if ("os".equals(prefix))
return "http://a9.com/-/spec/opensearch/1.1/";
else if ("x".equals(prefix))
return "http://www.w3.org/1999/xhtml";
else if ("xml".equals(prefix))
return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}
// This method isn't necessary for XPath processing.
public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}
// This method isn't necessary for XPath processing either.
public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}
}
Then just use it, which (thankfully) doesn't take much time at all:
然后就使用它,这(谢天谢地)根本不需要太多时间:
return Integer.parseInt(xpath.evaluate("/a:feed/os:totalResults/text()", document));
回答by Russell Leggett
Use XSLT. Seriously. This is a perfect job for it. Just use a copy template to copy everything as is except for the place where you need to add more xml. You can even add the XML by actually writing XML instead of DOM manipulation.
使用 XSLT。严重地。这对它来说是一个完美的工作。只需使用复制模板复制所有内容,除了需要添加更多 xml 的地方。您甚至可以通过实际编写 XML 而不是 DOM 操作来添加 XML。
This is the copy template:
这是复制模板:
<xsl:template match="node() | @*">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
I know a lot of people hate XSLT, but this is a task where it would really shine and take almost no code. Also, you could just use what's in the JDK.
我知道很多人讨厌 XSLT,但这是一项非常有用的任务,它几乎不需要任何代码。此外,您可以只使用 JDK 中的内容。
回答by Lukas Eder
Since writing too much code is the main issue for you, you might want to consider jOOX:
由于编写太多代码是您的主要问题,您可能需要考虑 jOOX:
http://code.google.com/p/joox/
http://code.google.com/p/joox/
I have created jOOX to be a port of jQuery to Java. The underlying technology is Java's standard DOM. Some sample code:
我已经创建了 jOOX 作为 jQuery 到 Java 的端口。底层技术是Java 的标准DOM。一些示例代码:
// Find the order at index for and add an element "paid"
$(document).find("orders").children().eq(4)
.append("<paid>true</paid>");
// Find those orders that are paid and flag them as "settled"
$(document).find("orders").children().find("paid")
.after("<settled>true</settled>");
// Add a complex element
$(document).find("orders").append(
$("order", $("date", "2011-08-14"),
$("amount", "155"),
$("paid", "false"),
$("settled", "false")).attr("id", "13");
Note: Namespaces are not yet explicitly supported, but you can work around that
注意:命名空间尚未明确支持,但您可以解决这个问题
回答by Kevin
It sounds like you can write an xslt style sheet to do what you want.
听起来您可以编写一个 xslt 样式表来执行您想要的操作。

