Java生成和解析XML格式文件和字符串的实例代码


当然,我可以为你提供Java中生成和解析XML格式文件及字符串的示例代码。

### 生成XML字符串

使用`javax.xml.transform`包中的类可以方便地生成XML字符串。以下是一个简单的示例:


import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class XmlGenerator {
    public static String generateXml() throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();

        // 创建根元素
        Element root = doc.createElement("bookstore");
        doc.appendChild(root);

        // 添加子元素
        Element book = doc.createElement("book");
        root.appendChild(book);

        Element title = doc.createElement("title");
        title.appendChild(doc.createTextNode("Learning XML"));
        book.appendChild(title);

        // 转换为字符串
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new StringBuilder());
        transformer.transform(source, result);

        return result.getWriter().toString();
    }

    public static void main(String[] args) {
        try {
            String xml = generateXml();
            System.out.println(xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

### 解析XML字符串

使用`javax.xml.parsers`包中的类可以解析XML字符串。以下是一个示例,展示了如何解析之前生成的XML字符串:


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class XmlParser {
    public static void parseXml(String xmlString) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new java.io.ByteArrayInputStream(xmlString.getBytes()));

        // 获取根元素
        Element root = doc.getDocumentElement();

        // 遍历所有book元素
        NodeList books = root.getElementsByTagName("book");
        for (int i = 0; i < books.getLength(); i++) {
            Element book = (Element) books.item(i);

            // 获取book下的title元素
            Element title = (Element) book.getElementsByTagName("title").item(0);
            System.out.println("Book Title: " + title.getTextContent());
        }
    }

    public static void main(String[] args) {
        try {
            String xmlString = "<bookstore><book><title>Learning XML</title></book></bookstore>";
            parseXml(xmlString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意:在真实应用中,XML字符串`xmlString`可能来自于文件、网络或其他源,而不是像示例中那样硬编码在代码中。此外,对于复杂的XML结构,可能需要更复杂的解析逻辑来提取所需的数据。