你是对的,使用标准的XML API,这不是一个好方法 – 这是一个例子(可能是错误的;它运行,但我很久以前写过它).
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()来获得第一个孩子,但问题是如果root和child元素之间有任何空格,那么将创建一个Text节点.树,你将获得该节点而不是实际的元素节点.该程序的输出是:
D:\home\tmp\xml>java Proc
blahblah
如果你不需要它,我认为你可以压缩xml版本字符串,但我不确定.如果可能的话,我可能会尝试使用第三方XML库.