小编典典
没错,使用标准XML API并不是一种好方法-这是一个示例(可能是bug缠身;它可以运行,但是我很久以前就写了)。
import javax.xml.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import java.io.*;
public class Proc
{
public static void main(String[] args) throws Exception
{
//Parse the input document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("in.xml"));
//Set up the transformer to write the output string
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
//Find the first child node - this could be done with xpath as well
NodeList nl = doc.getDocumentElement().getChildNodes();
DOMSource source = null;
for(int x = 0;x < nl.getLength();x++)
{
Node e = nl.item(x);
if(e instanceof Element)
{
source = new DOMSource(e);
break;
}
}
//Do the transformation and output
transformer.transform(source, result);
System.out.println(sw.toString());
}
}
似乎您可以仅使用doc.getDocumentElement()。getFirstChild()来获得第一个孩子,但是问题是如果根元素和子元素之间存在任何空格,则会在树,您将获得该节点,而不是实际的元素节点。该程序的输出为:
D:\home\tmp\xml>java Proc
blahblah
我认为您可以在不需要的情况下取消xml版本字符串,但是我不确定。如果可能的话,我可能会尝试使用第三方XML库。
2020-10-15