FredoAF
FredoAF

Reputation: 504

XML edit all tags with the same name in Java

I have the values and the tag string I wish to change. But in my scenario I cannot be certain of the xml structure.

I wish to do a simple function such as this:

for tag.equals(tagValue){
   if found{
      oldTagText=newValue
   }
}

So all tags that match will be changed regardless of structure. Anyone know how to do this?

Upvotes: 0

Views: 156

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

The simplest way to do it is SAX:

    String xml = "<root><e1>xxx</e1></root>";
    XMLFilterImpl xmlReader = new XMLFilterImpl(
            XMLReaderFactory.createXMLReader()) {

        @Override
        public void startElement(String uri, String localName,
                String qName, Attributes atts) throws SAXException {
            super.startElement(uri, localName, tagName(qName), atts);
        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            super.endElement(uri, localName, tagName(qName));
        }

        private String tagName(String qName) {
            if (qName.equals("e1")) {
                return "e2";
            }
            return qName;
        }
    };
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    StringWriter s = new StringWriter();
    t.transform(new SAXSource(xmlReader, new InputSource(new StringReader(
            xml))), new StreamResult(s));
    System.out.println(s);

Upvotes: 0

Puce
Puce

Reputation: 38122

If you want to do the replacement in Java rather than XSL then have a look at StAX: http://docs.oracle.com/javase/tutorial/jaxp/stax/index.html

(Note: For most StAX use cases it's recommended to use the StAX iterator API (event based), AFAIK.)

Upvotes: 1

Related Questions