Java SAX Parser命名空间抛出NullPointerException

时间:2013-10-03 16:13:13

标签: java xml parsing namespaces sax

我想使用SAX Parser解析XML文档。 当文档不包含任何命名空间时,它完美地工作。但是,当我向根元素添加名称空间时,我面临着一个NullPointerException。

这是我正在使用的XML文档:

<?xml version="1.0" encoding="utf-8"?>
<Root>
   <Date>01102013</Date>
   <ID>1</ID>
   <Count>3</Count>
   <Items>
      <Item>
         <Date>01102013</Date>
         <Amount>100</Amount>
      </Item>
      <Item>
         <Date>02102013</Date>
         <Amount>200</Amount>
      </Item>
   </Items>
</Root>

这是有问题的版本:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.xyz.com/q">
   <Date>01102013</Date>
   <ID>1</ID>
   <Count>3</Count>
   <Items>
      <Item>
         <Date>01102013</Date>
         <Amount>100</Amount>
      </Item>
      <Item>
         <Date>02102013</Date>
         <Amount>200</Amount>
      </Item>
   </Items>
</Root>

这是我的代码:

Document doc = null;
SAXBuilder sax = new SAXBuilder();
sax.setFeature("http://xml.org/sax/features/external-general-entities", false);  
 // I set this as true but still nothing changes
sax.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
sax.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

doc = sax.build(xmlFile);   // xmlFile is a File object which is a function parameter

Root root = new Root();
Element element = doc.getRootElement();
root.setDate(element.getChild("Date").getValue());
root.setID(element.getChild("ID").getValue()); 
.
.
.

当我使用第一个XML时,它运行正常。当我使用第二个XML

element.getChild("Date").getValue()

返回null。

注意:我可以使用

阅读“http://www.xyz.com/q”部分
doc.getRootElement().getNamespaceURI();

这意味着我仍然可以访问根元素。

任何人都知道如何克服这个问题?

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以在XML文档中使用多个名称空间,每个元素可以拥有每个名称空间。为了访问普通文档中的文档元素(没有名称空间),您可以使用getChildgetAttribute等方法,这些方法只有一个参数,即子名称或属性名称。这是您在代码中使用的内容。

但是为了访问命名空间版本,您必须使用这些方法的另一个覆盖,这些方法具有类型Namespace的第二个参数。这样,您可以在给定命名空间的基础上查询元素的子元素或属性。因此,如果您想要阅读第二个文档(具有名称空间),您的代码将是这样的:

// The first parameter is the prefix of this namespace in your document. in your sample it's an empty string
Namespace ns = Namespace.getNamespace("", "http://www.xyz.com/q");

Element element = doc.getRootElement();
root.setDate(element.getChild("Date", ns).getValue());
root.setID(element.getChild("ID", ns).getValue());
相关问题