3
我將嘗試描述我的問題。 我有一個結構的XML文檔(不看俄文本;它是確定):如何使用Xpath正確傳遞XML中的對象
<Books>
<Book ganre="fantasy">
<bookId>FD46</bookId>
<bookName>Меч предназначения</bookName>
<bookAuthor>Анджей Сапковский</bookAuthor>
<bookYear>1994</bookYear>
<bookAvailable>false</bookAvailable>
</Book>
<Book ganre="fantasy">
<bookId>0RD7</bookId>
<bookName>Башня ласточки</bookName>
<bookAuthor>Анджей Сапковский</bookAuthor>
<bookYear>1997</bookYear>
<bookAvailable>false</bookAvailable>
</Book>
<Book ganre="action">
<bookId>709F</bookId>
<bookName>Автостопом по галактике</bookName>
<bookAuthor>Дуглас Адамс</bookAuthor>
<bookYear>1979</bookYear>
<bookAvailable>false</bookAvailable>
</Book>
</Books>
試圖通過bookID
與此XPath
FileInputStream fileInputStream = new FileInputStream("Test/Books.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(fileInputStream);
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
Node node = (Node) xPath
.evaluate("//Book[bookId/text()='" + bookID + "']", document.getDocumentElement(), XPathConstants.NODE);
bookID
的幫助找到元素 - 這是用戶輸入(例如,像這樣)
Scanner sc = new Scanner(System.in, "cp866");
String bookID;
bookID = sc.nextLine();
所以想法是從XML節點從這個對象,我們目前的ID在一個字符串01發現返回所以我可以放入另一個xml。
像
String takenBookName = new XMLDocument(xml).xpath("/Books/Book/bookName/text").get(0); //it will doesnt work ;)
請加最後一個元素(這樣的人可以複製/粘貼) –
@DmytroPastovenskyi解決 – TheOriginalNickname
我剛剛與http://www.freeformatter.com/xpath-tester.html#ad-output檢查。 您的請求在那裏工作。你可以再次檢查XML和你的xpath嗎? –