2013-10-03 4 views
2

SAX 파서를 사용하여 XML 문서를 구문 분석하려고합니다. 문서에 네임 스페이스가 포함되어 있지 않으면 문서가 완벽하게 작동합니다. 그러나 루트 요소에 네임 스페이스를 추가하면 NullPointerException이 발생합니다.Java SAX Parser 네임 스페이스 예외 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() 

을 반환합니다.

참고 : 나는 여전히 루트 요소를 액세스 할 수 있습니다

doc.getRootElement().getNamespaceURI(); 

를 사용하여 "http://www.xyz.com/q"부분을 읽을 수.

누구나이를 극복하는 방법을 알고 있습니까?

미리 감사드립니다.

답변

1

XML 문서에서 여러 네임 스페이스를 사용할 수 있으며 각 요소는 각각의 네임 스페이스를 가질 수 있습니다. 네임 스페이스가없는 일반 문서의 문서 요소에 액세스하려면 getChild 또는 getAttribute과 같은 메서드를 사용할 수 있습니다.이 메서드에는 자식 이름 또는 특성 이름이 하나뿐입니다. 이것은 당신이 당신의 코드에서 사용한 것입니다.

그러나 네임 스페이스 버전에 액세스하려면 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()); 
+0

나는 같이 넣어했습니다 그것은 일 : element.getChild ("날짜"문서를 .getNamespace()). getValue() 답변 해 주셔서 감사합니다! –