【发布时间】:2018-12-06 12:07:44
【问题描述】:
假设xml文件是这样的:
<!DOCTYPE html [
<!ENTITY ldquo "♥">
]>
<DATA>
<ROW>
<Id>29855</Id>
<content><p>Did the summer fly as fast “</p>
<a href="https://www.ex.com/" target="_blank"></content>
<ROW>
<ROW>
<Id>11223</Id>
<content><p>Fly as fast “</p>
<a href="https://www.ex.com/" target="_blank"></content>
<ROW>
</DATA>
要求是从xml中获取“id”和“content”。内容应采用 html 结构,因为它存在于 xml 文件中。喜欢:
<p>Fly as fast “</p>
<a href="https://www.ex.com/" target="_blank">
我试过了,但我得到的是字符串格式的内容,比如:Fly as fast “
这是我用来解析 xml 的代码:
File fXmlFile = new File("D:\\customer_connect_posts.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("ROW");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
/*System.out.println("Staff id : "
+ eElement.getAttribute("Name"));*/
System.out.println("First Name : "
+ eElement.getElementsByTagName("Id")
.item(0).getTextContent());
System.out.println("Last Name : "
+ eElement.getElementsByTagName("content").item(0).getTextContent())
);
}
}
} catch (Exception e) {
e.printStackTrace();
}
问题是我正在调用返回文本的“getTextContent()”方法。有没有其他方法可以做到这一点。 需要帮助...
【问题讨论】:
标签: java xml xml-parsing