我正在使用 org.w3c.dom 来解析 XML 文件。然后我需要返回特定节点的整个 XML,包括标签,而不仅仅是标签的值。我使用 NodeList 是因为我需要计算文件中有多少条记录。但我还需要从头开始批量读取该文件,然后将其写入一个新的 XML 文件。但我当前的代码只打印节点的值,而不打印节点本身。我被难住了。
public static void main(String[] args) {
try {
File fXmlFile = new File (args[0]);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList listOfRecords = doc.getElementsByTagName("record");
int totalRecords = listOfRecords.getLength();
System.out.println("Total number of records : " + totalRecords);
int amountToSplice = queryUser();
for (int i = 0; i < amountToSplice; i++) {
String stringNode = listOfRecords.item(i).getTextContent();
System.out.println(stringNode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
最佳答案
getTextContent()只会“返回该节点及其后代的文本内容”,即您只获得“文本”类型节点的内容。解析 XML 时,最好记住有几种不同类型的节点,请参阅 XML DOM Node Types .
要做你想做的事,你可以创建一个像这样的实用方法......
public static String nodeToString(Node node)
{
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString();
}
然后像这样循环并打印...
for (int i = 0; i < amountToSplice; i++)
System.out.println(nodeToString(listOfRecords.item(i)));
关于java - 如何使用 DOM 解析器检索包含标签的 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16972314/