java操作XML实例代码


以下是一个简单的Java操作XML的实例代码,使用了Java内置的`DocumentBuilder`和`Transformer`类来读取和写入XML文件。这个例子将展示如何读取一个XML文件,修改其内容,并保存回文件。


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 org.w3c.dom.NodeList;

public class XMLExample {

    public static void main(String[] args) {
        try {
            // 读取XML文件
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse("input.xml"); // 假设input.xml是你要读取的XML文件

            // 假设我们要修改第一个<book>元素的<title>
            NodeList books = document.getElementsByTagName("book");
            if (books.getLength() > 0) {
                Element book = (Element) books.item(0);
                NodeList titles = book.getElementsByTagName("title");
                if (titles.getLength() > 0) {
                    Element title = (Element) titles.item(0);
                    title.setTextContent("新书名"); // 修改书名
                }
            }

            // 将修改后的Document写回到文件
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // 格式化输出

            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(new java.io.File("output.xml")); // 保存到output.xml

            transformer.transform(source, result);

            System.out.println("XML文件已成功修改并保存!");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

注意:

- 示例中假设你有一个名为`input.xml`的XML文件,并且它包含至少一个``元素。

- 修改了第一个``元素的``标签的内容为"新书名"。</p><p>- 修改后的XML被保存到名为`output.xml`的文件中。</p><p>- 请确保你的项目中已经正确导入了处理XML所需的库,通常Java标准库已经包含了这些类。</p><p>- 异常处理仅用于演示目的,实际项目中可能需要更详细的错误处理逻辑。</p> </div> </div> </div> </div> <div class="row"> <div class="card card-body"> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8670312724662002" crossorigin="anonymous"></script> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-8670312724662002" data-ad-slot="5669508194"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> </div> <hr> <footer class="card" style="position:relative;bottom:0;width:100%;"> <div style="background-color: #e9ecef;padding-top: 20px;"> <div class="container"> <div class="copyright">Copyright © 2024 www.d2tu.com <a rel="nofollow" href="https://beian.miit.gov.cn/" target="_blank">皖ICP备2023005503号-1</a> <a href="https://www.d2tu.com/sitemap.xml" target="_blank">XML地图</a> </div> <p>QQ邮箱: <b>664032890</b></p> </div> </div> </footer> <script src="/static/js/jquery.min.js"></script> <script src="/static/js/bootstrap.min.js"></script> <script src="/ziyuan/js/prism.js"></script> </body> </html>