【问题标题】:Writing to an XML File in Java用 Java 写入 XML 文件
【发布时间】:2012-03-29 19:57:23
【问题描述】:

我有一个 XML 文件,其中有一个如图所示的元素;

"<Event start="2011.12.12 13:45:00:0000" end="2011.12.12 13:47:00:0000" anon="89"/>"

我想添加另一个属性“comment”并将其写入此 XML 文件给;

"<Event start="2011.12.12 13:45:00:0000" end="2011.12.12 13:47:00:0000" anon="89" comment=""/>"

我该怎么做呢?

谢谢,马特

【问题讨论】:

标签: java xml parsing


【解决方案1】:

解析文件,添加属性并将其写回磁盘。

有很多框架可以做到这一点。 Java 中的 DOM 框架可能是您应该首先查看的内容。

【讨论】:

  • 我已经解析了 xml 文件的所有元素,并尝试 setAttribute("comment", "")。但它什么也没做。
【解决方案2】:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
Document document = factory.newDocumentBuilder().parse(xmlFile);

Element eventElement = (Element)document.getElementsByTagName("Event").item(0);
eventElement.setAttribute("comment", "");

仅供参考:我在这里使用了 DOM 框架 org.w3c.dom.*

【讨论】:

    【解决方案3】:

    使用setAttribute方法添加属性,

    // Add an attribute
    element.setAttribute("newAttrName", "attrValue");
    

    使用以下方法写入XML文件,

    // This method writes a DOM document to a file
    public static void writeXmlFile(Document doc, String filename) {
        try {
            // Prepare the DOM document for writing
            Source source = new DOMSource(doc);
    
            // Prepare the output file
            File file = new File(filename);
            Result result = new StreamResult(file);
    
            // Write the DOM document to the file
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
        } catch (TransformerException e) {
        }
    }
    

    【讨论】:

    • 感谢您的帮助! :D 现在完成了!
    【解决方案4】:

    使用 DOM,正如之前的答案所建议的,对于这个相对简单的特定问题当然是合理的。

    但是,我发现当您想要解析和/或修改 XML 文件时,JDOM 通常更容易使用。它的基本方法是将整个文件加载到一个易于使用的数据结构中。除非您的 XML 文件非常大,否则此方法效果很好。

    欲了解更多信息,请转到http://www.jdom.org/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-19
      • 2011-07-21
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多