Java String to XML 之 将字符串解析为XML DOM示例

在Java中,XML用org.w3c.dom.Document对象表示。在本XML教程中,我们将学习-

  1. 将XML 字符串转换为XML文档
  2. XML文件内容转换为XML文档

1)将字符串转换为XML文档

要将XML字符串转换为XML Dom,我们需要以下类:

  • javax.xml.parsers.DocumentBuilder:定义API,以从来自各种输入源的XML内容中获取XML DOM Document实例。这些输入源是InputStreams,Files,URL和SAX InputSources。
  • javax.xml.parsers.DocumentBuilderFactory:定义一个工厂API,使应用程序能够获取解析器(DocumentBuilder),该解析器从XML内容生成DOM对象树。
  • org.w3c.dom.Document:它表示整个XML DOM。从概念上讲,它是文档树的根,并通过工厂方法提供对文档数据的访问,直到树的下层。
  • java.io.StringReader:从字符串内容创建 Stream 。DocumentBuilder使用此 Stream 读取XML内容进行解析。
StringtoXMLExample.java
package com.how2codex.demo;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class StringtoXMLExample
{
    public static void main(String[] args)
    {
        final String xmlStr = "<employees>" +
                                "   <employee id=\"101\">" +
                                "        <name>Saigon</name>" +
                                "       <title>Author</title>" +
                                "   </employee>" +
                                "   <employee id=\"102\">" +
                                "        <name>Brian Lara</name>" +
                                "       <title>Cricketer</title>" +
                                "   </employee>" +
                                "</employees>";
        
        //Use method to convert XML string content to XML Document object
        Document doc = convertStringToXMLDocument( xmlStr );
        
        //Verify XML document is build correctly
        System.out.println(doc.getFirstChild().getNodeName());
    }
    private static Document convertStringToXMLDocument(String xmlString)
    {
        //Parser that produces DOM object trees from XML content
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        //API to obtain DOM Document instance
        DocumentBuilder builder = null;
        try
        {
            //Create DocumentBuilder with default configuration
            builder = factory.newDocumentBuilder();
            
            //Parse the content to Document object
            Document doc = builder.parse(new InputSource(new StringReader(xmlString)));
            return doc;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
//Output:
employees

2)将XML文件转换为XML文档

要从XML文件获取XML dom,而不是将XML字符串传递给,而是传递DocumentBuilder文件路径以使解析器直接读取文件内容。

我们有employees.xml包含XML内容的文件,我们将阅读以获取XML文档。

员工.xml
<employees>
    <employee id="101">
         <name>Saigon</name>
        <title>Author</title>
    </employee>
    <employee id="102">
         <name>Brian Lara</name>
        <title>Cricketer</title>
    </employee>
</employees>
StringtoXMLExample.java
package com.how2codex.demo;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class StringtoXMLExample
{
    public static void main(String[] args)
    {
        final String xmlFilePath = "employees.xml";
        
        //Use method to convert XML string content to XML Document object
        Document doc = convertXMLFileToXMLDocument( xmlFilePath );
        
        //Verify XML document is build correctly
        System.out.println(doc.getFirstChild().getNodeName());
    }
    private static Document convertXMLFileToXMLDocument(String filePath)
    {
        //Parser that produces DOM object trees from XML content
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        
        //API to obtain DOM Document instance
        DocumentBuilder builder = null;
        try
        {
            //Create DocumentBuilder with default configuration
            builder = factory.newDocumentBuilder();
            
            //Parse the content to Document object
            Document doc = builder.parse(new File(filePath));
            return doc;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
}
//Output:
employees

如果您有任何疑问,请在评论区留言,我会一一解答。

This entry was posted in   Xml.
Bookmark the   permalink.

saigon has written 1445 articles

Leave a Reply