我目前正在修改一段代码,我想知道XML的格式化方式(制表符和空格)是否会影响将其解析为DocumentBuilderFactory类的方式。
本质上,问题是is...can,我向DocumentBuilderFactory传递了一个没有空格的长字符串,或者它是否需要以某种方式格式化?
提前感谢,下面是来自Oracle网站的类定义。
DocumentBuilderFactory类
“定义工厂API,使应用程序能够获得从XML文档生成DOM对象树的解析器。”
发布于 2010-08-04 18:05:35
只要字符串是有效的 XML,它就不会影响解析器的能力。制表符和换行符被解析器剥离或忽略,实际上是为了满足人类读者的审美感。
注您必须将输入流(例如,StringBufferInputStream)传递给DocumentBuilder,因为字符串版本的解析假定它是指向XML。
发布于 2010-09-24 22:55:17
文档会有所不同。制表符和新行将转换为文本节点。您可以在DocumentBuilderFactory上使用以下方法消除这些问题:
但是,为了使其正常工作,您必须设置DOM解析器来根据DTD或xml模式验证内容。
或者,您也可以通过编程方式自行删除多余的空格,方法如下:
public static void removeEmptyTextNodes(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode;
for (int x = nodeList.getLength() - 1; x >= 0; x--) {
childNode = nodeList.item(x);
if (childNode.getNodeType() == Node.TEXT_NODE) {
if (childNode.getNodeValue().trim().equals("")) {
node.removeChild(childNode);
}
} else if (childNode.getNodeType() == Node.ELEMENT_NODE) {
removeEmptyTextNodes(childNode);
}
}
}发布于 2010-09-24 07:54:12
DocumentBuilder为带换行符xml string和不带换行符的xml string构建不同的DOM对象。下面是我测试的代码:
StringBuilder sb = new StringBuilder();
sb.append("<root>").append(newlineChar).append("<A>").append("</A>").append(newlineChar).append("<B>tagB").append("</B>").append("</root>");
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputStream xmlInput = new ByteArrayInputStream(sb.toString().getBytes());
Element documentRoot = builder.parse(xmlInput).getDocumentElement();
NodeList nodes = documentRoot.getChildNodes();
System.out.println("How many children does the root have? => "nodes.getLength());
for(int index = 0; index < nodes.getLength(); index++){
System.out.println(nodes.item(index).getLocalName());
}
输出:
How many children does the root have? => 4
null
A
null
B
但是,如果从StringBuilder中删除新的newlineChar,则输出为:
How many children does the root have? => 2
A
B
这表明DocumentBuilder生成的DOM对象是不同的。
https://stackoverflow.com/questions/3404391
复制相似问题