【发布时间】:2016-02-05 22:46:35
【问题描述】:
我有以下 XML:
<?xml version="1.0"?>
<doOrchestration xmlns="http://comResponse.engine/response">
<response uuid="86db9b58-312b-4cbb-8aa5-df3663884291">
<headers>
<header name="Content-Type">application/xml</header>
<header name="Server">local-C++</header>
</headers>
<responseCode>200</responseCode>
<content><![CDATA[<explanation></explanation>]]></content>
</response>
</doOrchestration>
我想从内容节点中解析出如下文本:
<![CDATA[<explanation></explanation>]]>
注意这里的内容是用 CDATA 标签包裹的。如何使用任何方法在 Java 中完成此操作。
这是我的代码:
@Test
public void testGetDoOrchResponse() throws IOException {
String path = "/Users/haddad/Git/Tools/ContentUtils/src/test/resources/testdata/doOrch_testfiles/doOrch_response.xml";
File f = new File(path);
String response = FileUtils.readFileToString(f);
String content = getDoOrchResponse(response, "content");
System.out.println("Content: "+content);
}
// 输出:内容:空白
static String getDoOrchResponse(String xml, String tagFragment) throws FileNotFoundException {
String content = new String();
try {
Document doc = getDocumentXML(xml);
NodeList nlNodeExplanationList = doc.getElementsByTagName("response");
for(int i=0;i<nlNodeExplanationList.getLength();i++) {
Node explanationNode = nlNodeExplanationList.item(i);
List<String> titleList = getTextValuesByTagName((Element)explanationNode, tagFragment);
content = titleList.get(0);
}
}
catch (IOException e) {
e.printStackTrace();
}
return content;
}
static List<String> getTextValuesByTagName(Element element, String tagName) {
NodeList nodeList = element.getElementsByTagName(tagName);
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < nodeList.getLength(); i++) {
String textValue = getTextValue(nodeList.item(i));
if(textValue.equalsIgnoreCase("") ) {
textValue = "blank";
}
list.add(textValue);
}
return list;
}
static String getTextValue(Node node) {
StringBuffer textValue = new StringBuffer();
int length = node.getChildNodes().getLength();
for (int i = 0; i < length; i ++) {
Node c = node.getChildNodes().item(i);
if (c.getNodeType() == Node.TEXT_NODE) {
textValue.append(c.getNodeValue());
}
}
return textValue.toString().trim();
}
static Document getDocumentXML(String xml) throws FileNotFoundException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
Document doc = null;
try {
db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));
doc.getDocumentElement().normalize();
}
catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return doc;
}
我做错了什么?为什么我得到空白作为输出?我只是没看到...
【问题讨论】:
-
如果你真的想返回
<![CDATA[<explanation></explanation>]]>那么你需要用LSSerializer序列化content元素的子节点。但是由于 CDATA 部分是避免转义标记的语法糖,因此人们通常希望将content元素的内容作为字符串读出,并使用getTextContent()给出该字符串,无论内部存在 CDATA 部分还是普通文本节点。 -
你能给我看一下序列化的例子吗,对不起我是菜鸟
标签: java xml xpath xml-parsing