程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> xml-初學JAVA-XML遇到的問題,求指教

xml-初學JAVA-XML遇到的問題,求指教

編輯:編程綜合問答
初學JAVA-XML遇到的問題,求指教

題目:獲得下圖xml文件中第二個linkname中的name的內容,也就是“小李”

圖片說明

圖片說明

貼代碼:


小蔡
[email protected]
成都
源代碼教育

<linkman id="2">
    <name>小李</name>
    <email>[email protected]</email>
    <address>昆明</address>
    <group>寰宇旅遊</group>
</linkman>

再貼:

public class GetNameTest {
@Test
public void getnametest() throws Exception {
//1,取得XML的document對象
File file = new File("D:/workspace2/1-16-xml/src/cn/itsource/xml/condacts.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);

    //2,取得xml的根元素
    Element rootEle = doc.getDocumentElement();

    //3,拿到目標name所在的第二個linkman
    NodeList linkManList = rootEle.getElementsByTagName("linkname");
    //上一句拿到的是所有linkman集合,遍歷出所有linkman
    for(int i = 0;i<linkManList.getLength();i++){
        Node linkManNode = linkManList.item(i);
    }
    //拿到第二個linkman,並強轉成元素對象
    Element linkManEle = (Element) linkManList.item(1);

    //4,拿到linkman中的name元素
    NodeList nameList = linkManEle.getElementsByTagName("name");
    //上一句返回值雖然還是個集合,但是name就一個,因此不用遍歷了,直接取
    Node getname = nameList.item(0);
    //拿到name中的文本元素
    System.out.println(getname.getTextContent());
}

}

最佳回答:


為什麼不貼代碼呢?貼代碼還可以幫忙測一下,這個圖讓回答者敲代碼是很糾結的事情呢。把代碼貼出來呗,我有空幫你測測問題。

cai772088996
cai772088996
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved