java将字符串转换为xml并解析节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19661047/
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
java convert string to xml and parse node
提问by Doc Holiday
Hello I am getting back a string from a webservice.
您好,我从网络服务中取回一个字符串。
I need to parse this string and get the text in error message?
我需要解析这个字符串并获取错误消息中的文本吗?
My string looks like this:
我的字符串看起来像这样:
<response>
<returnCode>-2</returnCode>
<error>
<errorCode>100</errorCode>
<errorMessage>ERROR HERE!!!</errorMessage>
</error>
</response>
Is it better to just parse the string or convert to xml then parse?
是只解析字符串还是转换为 xml 然后解析更好?
采纳答案by azz
I'd use Java's XML document libraries. It's a bit of a mess, but works.
我会使用 Java 的 XML 文档库。这有点乱,但有效。
String xml = "<response>\n" +
"<returnCode>-2</returnCode>\n" +
"<error>\n" +
"<errorCode>100</errorCode>\n" +
"<errorMessage>ERROR HERE!!!</errorMessage>\n" +
"</error>\n" +
"</response>";
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new InputSource(new StringReader(xml)));
NodeList errNodes = doc.getElementsByTagName("error");
if (errNodes.getLength() > 0) {
Element err = (Element)errNodes.item(0);
System.out.println(err.getElementsByTagName("errorMessage")
.item(0)
.getTextContent());
} else {
// success
}
回答by Brian Agnew
It's an XML document. Use an XML parser.
它是一个 XML 文档。使用 XML 解析器。
You couldtease it apart using string operations. But you have to worry about entity decoding, character encodings, CDATA sections etc. An XML parser will do all of this for you.
您可以使用字符串操作将其分开。但是您必须担心实体解码、字符编码、CDATA 部分等。XML 解析器将为您完成所有这些工作。
Check out JDOMfor a simpler XML parsing approach than using raw DOM/SAX implementations.
查看JDOM以获得比使用原始 DOM/SAX 实现更简单的 XML 解析方法。
回答by Paul Richards
I would probably use an XML parser to convert it into XML using DOM, then get the text. This has the advantage of being robust and coping with any unusual situations such as a line like this, where something has been commented out:
我可能会使用 XML 解析器使用 DOM 将其转换为 XML,然后获取文本。这具有健壮性和应对任何异常情况的优点,例如像这样的行,其中某些内容已被注释掉:
<!-- commented out <errorMessage>ERROR HERE!!!</errorMessage> -->
If you try and parse it yourself then you might fall foul of things like this. Also it has the advantage that if the requirements expand, then its really easy to change your code.
如果您尝试自己解析它,那么您可能会遇到这样的事情。它还有一个优点,如果需求扩展,那么更改代码真的很容易。
http://docs.oracle.com/cd/B28359_01/appdev.111/b28394/adx_j_parser.htm
http://docs.oracle.com/cd/B28359_01/appdev.111/b28394/adx_j_parser.htm