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 を使用すると、正常に動作します。2 番目の XML を使用する場合
element.getChild("Date").getValue()
null を返します。
注: 「 http://www.xyz.com/q」の部分は次を使用して読み取ることができます
doc.getRootElement().getNamespaceURI();
つまり、ルート要素には引き続きアクセスできます。
これを克服する方法を知っている人はいますか?
前もって感謝します。