在java中使用DOM对XML的解析

通过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中的值

posted on 2007-10-15 16:22 刘铮 阅读(243) 评论(0)  编辑  收藏 所属分类: JAVA General


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

留言簿(1)

文章分类(141)

文章档案(147)

搜索

最新评论