使用Java将XML元素包装为文本?

时间:2009-12-31 03:10:06

标签: java xml xslt

我想像这样转换XML:

<account>Wally World</account>
<city>Anywhere</city>
<state>CA</state>

通过用等号和单引号(即=''

)包装每个元素来实现此目的
<account>='Wally World'</account>
<city>='Anywhere'</city>
<state>='CA'</state>

需要使用Java转换大型XML文件中的所有元素文本,可能使用XSLT吗?

2 个答案:

答案 0 :(得分:2)

在XSLT中,它可能是这样的:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

    <xsl:template match="account|city|state">
        <xsl:element name="{local-name(.)}">
            <xsl:text disable-output-escaping="yes">=&apos;</xsl:text>
            <xsl:value-of select="text()"/>
            <xsl:text disable-output-escaping="yes">&apos;</xsl:text>
        </xsl:element>
    </xsl:template>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

请注意,它只会更改帐户,城市和州元素,并保留所有其他元素。所以这样的文件:

<items>
    <item>
        <account>Wally World</account>
        <city>Anywhere</city>
        <state>CA</state>
    </item>
</items>

......会变成这样:

<items>
    <item>
        <account>='Wally World'</account>
        <city>='Anywhere'</city>
        <state>='CA'</state>
    </item>
</items>

答案 1 :(得分:1)

如果您只想使用SAX进行此类简单更改,请输入以下代码:

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;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class XMLPipeline {

    public static void main(String[] args) throws Exception {
        String inputFile = "a.xml";
        PrintStream outputStream = System.out;
        new XMLPipeline().process(inputFile, outputStream);
    }

    //default JDK
    public void process(String inputFile, OutputStream outputStream) throws
            SAXException, ParserConfigurationException, IOException, TransformerException {
        StreamResult xwriter = new StreamResult(outputStream);
        XMLReader xreader = XMLReaderFactory.createXMLReader();
        XMLAnalyzer analyzer = new XMLAnalyzer(xreader);
        TransformerFactory stf = SAXTransformerFactory.newInstance();
        SAXSource ss = new SAXSource(analyzer, new InputSource(inputFile));
        stf.newTransformer().transform(ss, xwriter);
    }

    public static class XMLAnalyzer extends XMLFilterImpl {

        private Set<String> tags = new HashSet<String>(Arrays.asList("account", "city", "state"));
        boolean bufferText = false;
        StringBuilder buffer;

        public XMLAnalyzer(XMLReader xmlReader) {
            super(xmlReader);
        }


        @Override
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            super.startElement(uri, localName, qName, atts);
            if (tags.contains(localName)) {
                buffer = new StringBuilder("='");
                bufferText = true;
            }
        }

        @Override
        public void characters(char[] chars, int i, int i1) throws SAXException {
            if (bufferText) {
                buffer.append(chars, i, i1);
            } else {
                super.characters(chars, i, i1);
            }
        }

        @Override
        public void endElement(String s, String s1, String s2) throws SAXException {
            if (bufferText) {
                buffer.append('\'');
                super.characters(buffer.toString().toCharArray(), 0, buffer.length());
                bufferText = false;
            }
            super.endElement(s, s1, s2);
        }

    }
}