Adding namespace prefix XML String using XML DOM

邮差的信 提交于 2019-12-01 12:06:12

We can do it with Transformer + SAX. Try this:

    import java.io.StringWriter;

    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.stream.StreamResult;

    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.XMLFilterImpl;
    import org.xml.sax.helpers.XMLReaderFactory;

    public class Test {

        public static void main(String args[]) throws Exception {
            XMLReader xmlReader = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
                String namespace = "http://www.tibco.com/schemas/BWStatistics-hawk/Schema.xsd2";
                String pref = "ns0:";

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

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    super.endElement(namespace, localName, pref + qName);
                }
            };
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            StringWriter s = new StringWriter();
            t.transform(new SAXSource(xmlReader, new InputSource("test.xml")), new StreamResult(s));
            System.out.println(s);
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!