java解析xml问题,用Java解析XML时出现问题

I got some trouble parsing an XML document. For some reason, there are text nodes where I would not expect them to be and therefore my test turns red. The XML file looks like this:

PR1

one

two

DG1

three

ZBK

four

Now I have this snippet of code which can reproduce the error:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(TestHL7Helper.class.getResourceAsStream("TestHL7HelperInput.xml"));

Node root = doc.getFirstChild();

Node pr1 = root.getFirstChild();

Inspecting the root variable yields [RootNode: null] which seems to be right, but then it somehow goes all wrong. The pr1 variable turns out to be a text node [#text:\n ] - but why does the parser think that the new line and the spaces are a text node? Shouldn't that be ignored? I tried changing the encoding but that did not help either. Any ideas on that?

If I remove all new lines and space and have my XML document in just one line it all works fine...

解决方案

XML supports mixed content meaning elements can have both text and element child nodes. This is to support use cases like the following:

I've bolded the important part.

input.xml

This means that by default a DOM parser will treat the whitespace nodes in the following document as significant (below is a simplified version of your XML document):

PR1

Demo Code

If you have an XML schema you can set the ignoringElementContentWhitespace property on the DocumentBuilderFactory since then the DOM parser will know if and when the whitespace is significant.

import java.io.File;

import javax.xml.XMLConstants;

import javax.xml.parsers.*;

import javax.xml.validation.*;

import org.w3c.dom.Document;

public class Demo {

public static void main(String[] args) throws Exception {

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

Schema s = sf.newSchema(new File("src/forum16231687/schema.xsd"));

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

dbf.setSchema(s);

dbf.setIgnoringElementContentWhitespace(true);

DocumentBuilder db = dbf.newDocumentBuilder();

Document d = db.parse(new File("src/forum16231687/input.xml"));

System.out.println(d.getDocumentElement().getChildNodes().getLength());

}

}

schema.xsd

If you create schema.xsd that looks like the following then the demo code will report that the root element has 1 child node.

If you change schema.xsd so that the RootNode has mixed content the demo code will report that the RootNode has 3 child nodes.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值