57.md 4.6 KB
Newer Older
W
wizardforcel 已提交
1
# Java 字符串到 XML – 将字符串解析为 XML DOM 示例
W
wizardforcel 已提交
2 3 4

> 原文: [https://howtodoinjava.com/xml/parse-string-to-xml-dom/](https://howtodoinjava.com/xml/parse-string-to-xml-dom/)

W
wizardforcel 已提交
5
在 Java 中,XML 用`org.w3c.dom.Document`对象表示。 在本 XML 教程中,我们将学习:
W
wizardforcel 已提交
6 7 8 9 10 11

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

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

W
wizardforcel 已提交
12
要将**将 XML 字符串转换为 XML Dom**,我们需要以下类:
W
wizardforcel 已提交
13

W
wizardforcel 已提交
14 15 16 17
*   [`javax.xml.parsers.DocumentBuilder`](https://docs.oracle.com/javase/10/docs/api/javax/xml/parsers/DocumentBuilder.html) :定义 API,以从来自各种输入源的 XML 内容中获取 XML DOM 文档实例。 这些输入源是`InputStreams`,文件,URL 和 SAX `InputSources`
*   [`javax.xml.parsers.DocumentBuilderFactory`](https://docs.oracle.com/javase/10/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) :定义一种工厂 API,使应用能够获取解析器(`DocumentBuilder`),该解析器从 XML 内容生成 DOM 对象树。
*   [`org.w3c.dom.Document`](https://docs.oracle.com/javase/10/docs/api/org/w3c/dom/Document.html) :它表示整个 XML DOM。 从概念上讲,它是文档树的根,并通过工厂方法提供对文档数据的访问,甚至深入到树中。
*   [`java.io.StringReader`](https://docs.oracle.com/javase/10/docs/api/java/io/StringReader.html) :根据字符串内容创建流。 `DocumentBuilder`使用此流读取 XML 内容进行解析。
W
wizardforcel 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

```java
package com.howtodoinjava.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>Lokesh Gupta</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`,请传递文件路径以使解析器直接读取文件内容。

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

```java
<employees>
	<employee id="101">
		 <name>Lokesh Gupta</name>
	    <title>Author</title>
	</employee>
	<employee id="102">
		 <name>Brian Lara</name>
	    <title>Cricketer</title>
	</employee>
</employees>

```

```java
package com.howtodoinjava.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

```

将我的问题放在评论部分。

学习愉快!