有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java将XML打印到控制台

我有以下代码:

import java.net.URL;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;



public class Main {

    private static Document loadTestDocument(String url) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        return factory.newDocumentBuilder().parse(new URL(url).openStream());
    }

    public static void main(String[] args) throws Exception {
        Document  doc = loadTestDocument("https://www.w3schools.com/xml/note.xml");
        System.out.println(doc.getElementsByTagName("note").item(0).getChildNodes().item(0).getNodeValue());
    }
}

就我而言,这应该将节点文本打印到java控制台,但它似乎什么也不打印。。。没有任何错误。 我做错了什么


共 (4) 个答案

  1. # 1 楼答案

    执行以下操作以获取文本内容

    doc.getElementsByTagName("note").item(0).getChildNodes().item(0).getTextContent()
    

    编辑 试试这个,有一些空节点

    int i;
     for(i = 0; i < doc.getElementsByTagName("note").item(0).getChildNodes().getLength(); i++){
         System.out.println(doc.getElementsByTagName("note").item(0).getChildNodes().item(i).getTextContent());
     }
    
  2. # 2 楼答案

    试试这个

      Document  doc = loadTestDocument("https://www.w3schools.com/xml/note.xml");
      doc.getDocumentElement().normalize();
      Element element =(Element)doc.getElementsByTagName("note").item(0);
    
      System.out.println(element.getElementsByTagName("to").item(0).getTextContent());
      System.out.println(element.getElementsByTagName("from").item(0).getTextContent());
    

    输出:

    托夫

    贾尼

  3. # 3 楼答案

    使用另一个api Jsoup,我们可以解析xml,并在控制台上将整个xml打印为字符串

    用下面的代码片段尝试一下:

    org.jsoup.nodes.Document document = Jsoup.parse(new URL("https://www.w3schools.com/xml/note.xml"), 5000);
            System.out.println("XML content : "+document.html());
    

    输出:

    <note> 
     <to>
      Tove
     </to> 
     <from>
      Jani
     </from> 
     <heading>
      Reminder
     </heading> 
     <body>
      Don't forget me this weekend!
     </body> 
    </note>
    
  4. # 4 楼答案

    零项为注意。它没有价值。使用以上代码打印Tove

    System.out.println(doc.getElementsByTagName("note").item(0).getChildNodes().item(1).getTextContent());