java解析xml字符串
时间: 2023-08-01 14:06:48 浏览: 45
在 Java 中解析 XML 字符串可以使用以下步骤:
1. 创建一个 DocumentBuilderFactory 对象,并设置它的相关属性。
2. 使用 DocumentBuilderFactory 创建一个 DocumentBuilder 对象。
3. 使用 DocumentBuilder 对象解析 XML 字符串,生成一个 Document 对象。
4. 从 Document 对象中获取需要的数据。
下面是一个示例代码:
```java
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 XmlParser {
public static void main(String[] args) throws Exception {
String xmlString = "<root><name>John</name><age>25</age></root>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(new StringReader(xmlString));
Document doc = builder.parse(inputSource);
String name = doc.getElementsByTagName("name").item(0).getTextContent();
String age = doc.getElementsByTagName("age").item(0).getTextContent();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
```
这个程序会输出以下内容:
```
Name: John
Age: 25
```