通过DOM模型可以对XML进行解析:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
You can now read a document from a file:
File f = . . .
Document doc = builder.parse(f);
Alternatively, you can use a URL:
URL u = . . .
Document doc = builder.parse(u);
You can even specify an arbitrary input stream:
InputStream in = . . .
Document doc = builder.parse(in);
Element root = doc.getDocumentElement();
注意如果使用这种解析方法的话:
会有空格产生
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
. . .
}
如果避免空格产生
If you expect only subelements, then you can ignore the whitespace:
for (int i = 0; i < children.getLength(); i++)
{
Node child = children.item(i);
if (child instanceof Element)
{
Element childElement = (Element) child;
. . .
}
}
Text textNode = (Text) childElement.getFirstChild();
String text = textNode.getData().trim();
getData()方法可以得到textNode中的值