我有了像這樣的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然後我得到所有的錯誤類型。 有什麼幫助嗎?