2014-12-04 34 views
-1

我有了像這樣的XML:獲取某個節點從XML在Java中不工作

<ListOfErrors> <Error> <ErrorCode>1</ErrorCode> <Severity>Critical</Severity> </Error> <Error> <ErrorCode>15414</ErrorCode> <Severity>Non-Critical</Severity> </Error> </ListOfErrors>

我想的是,通過接收錯誤代碼,我可以根據檢索其他值錯誤。例如,我收到錯誤1,我知道嚴重程度。

我這樣做:

 DocumentBuilderFactory factory = DocumentBuilderFactory 
       .newInstance(); 
     DocumentBuilder builder = factory.newDocumentBuilder(); 
     Document document = builder.parse(new File("file.xml")); 

     String xPathExpression = "//Error[ErrorCode=1]"; 

     XPath xpath = XPathFactory.newInstance().newXPath(); 
     NodeList nodes = (NodeList) xpath.evaluate(xPathExpression, 
       document, XPathConstants.NODESET); 
     System.out.println(nodes.getLength()); 
     Element firstElement = (Element)nodes.item(0);        
     System.out.println("Severity"+firstElement.getAttribute("Severity")); 

我知道它不工作,但我不知道我丟失,xPathExpression工作正常,因爲如果我把它僅僅作爲//錯誤和我打印nodes.getlength然後我得到所有的錯誤類型。 有什麼幫助嗎?

回答

2

您正在檢索ErrorCode = 1的錯誤節點,但該節點沒有屬性,因此firstElement.getAttribute(「Severity」)將不會檢索任何內容。

嚴重性實際上是錯誤的子節點,而不是屬性。要獲取該值,您需要循環訪問子節點(firstElement.getChildNodes())或更改XPath以直接獲取嚴重性(「Error [ErrorCode = 1]/Severity」)