如何使用Xpath从XML正确传递对象

时间:2015-09-28 12:01:14

标签: java xml xpath

我会尝试描述我的问题。 我有下一个结构的XML文档(不要看俄文文本;没关系):

<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="match_parent" >

<CheckBox
    android:id="@+id/checkBox1"
    android:weight="0.5"
    android:layout_width="0dip"
    android:layout_height="wrap_content" />


<TextView
android:id="@+id/textView_Item_Listview"
android:weight="0.5"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:padding="3dp"
android:text="gfhfgh"
android:textSize="25sp" />

</LinearLayout>

尝试在此Xpath的帮助下通过 <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

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(); 中找到当前id的THIS对象的xml节点返回,这样我就可以放入另一个xml。

喜欢

<bookName></bookName><bookAuthor></bookAuthor>

1 个答案:

答案 0 :(得分:1)

必须为你工作。

internal