2

I have an XML file of which I have an element as shown;

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

I want to add another attribute "comment" and write it to this XML File giving;

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

How would I go about doing this?

Thanks, Matt

1

4 Answers 4

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", "");

FYI: I've use DOM framework here org.w3c.dom.*

Sign up to request clarification or add additional context in comments.

Comments

0

Use setAttribute method to add attribute,

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

Use the following method to write to XML file,

// 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) {
    }
}

1 Comment

Thanks for the help! :D It is now completed!
0

Parse the file, add the attribute and write it back to disk.

There is plenty of frameworks that can do this. The DOM framework in Java is probably the first thing you should look at.

1 Comment

I have parsed all the elements of the xml file and I have tried to setAttribute("comment", ""). but it does nothing.
0

Using DOM, as suggested in previous answers, is certainly reasonable for this particular problem, which is relatively simple.

However, I have found that JDOM is generally much easier to use when you want to parse and/or modify XML files. Its basic approach is to load the entire file into an easy to use data structure. This works well unless your XML file is very very large.

For more info go to http://www.jdom.org/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.