根据标记值的变化将xml分成较小的一个

时间:2018-10-01 11:05:56

标签: java xml xml-parsing xslt-2.0 stax

<?xml version="1.0" encoding="UTF-16"?>
<ABC>
    <END />
    <Tables>
        <START>
            <row>
                <id>111</id>
                <name>abc</name>
                <deptId>1</deptId>
            </row>
            <row>
                <id>112</id>
                <name>abc1</name>
                <deptId>1</deptId>
            </row>
            <row>
                <id>113</id>
                <name>abc3</name>
                <deptId>1</deptId>
            </row>
            <row>
                <id>222</id>
                <name>def</name>
                <deptId>2</deptId>
            </row>
            <row>
                <id>333</id>
                <name>pqr</name>
                <deptId>2</deptId>
            </row>
            <row>
                <id>444</id>
                <name>xyz</name>
                <deptId>2</deptId>
            </row>
            <row>
                <id>555</id>
                <name>lmn</name>
                <deptId>3</deptId>
            </row>
            <row>
                <id>555</id>
                <name>lmn</name>
                <deptId>3</deptId>
            </row>
        </START>
    </Tables>
</ABC>

我有一个具有上述结构的xml。我必须根据不同的deptId将xml溅入3个xml中。 我必须根据标记值的变化将xml拆分为较小的XML。我的元素是deptId,其值在某些行之后已更改。 具有相同deptId的所有元素都在一个序列中。

所需的输出是: 最好将xml名称作为部门ID。

第一个xml名称为1.xml

<?xml version="1.0" encoding="UTF-16"?>
<ABC>
    <END />
    <Tables>
        <START>
            <row>
                <id>111</id>
                <name>abc</name>
                <deptId>1</deptId>
            </row>
            <row>
                <id>112</id>
                <name>abc1</name>
                <deptId>1</deptId>
            </row>
            <row>
                <id>113</id>
                <name>abc3</name>
                <deptId>1</deptId>
            </row>
        </START>
    </Tables>
</ABC>

名称为2.xml的第二个xml:

<?xml version="1.0" encoding="UTF-16"?>
<ABC>
    <END />
    <Tables>
        <START>
            <row>
                <id>222</id>
                <name>def</name>
                <deptId>2</deptId>
            </row>
            <row>
                <id>333</id>
                <name>pqr</name>
                <deptId>2</deptId>
            </row>
            <row>
                <id>444</id>
                <name>xyz</name>
                <deptId>2</deptId>
            </row>
        </START>
    </Tables>
</ABC>

名称为3.xml的第三个xml:

<?xml version="1.0" encoding="UTF-16"?>
<ABC>
    <END />
    <Tables>
        <START>
            <row>
                <id>113</id>
                <name>abc3</name>
                <deptId>1</deptId>
            </row>
        </START>
    </Tables>
</ABC>

我通过引用几个选项尝试了StAXSource选项 我尝试过的选项是通过引用以下链接

Split xml Split large xml

这是已尝试的示例代码。

import java.io.File;
import java.io.FileReader;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;

public class Demo2 {

public static void main(String[] args) throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = xif.createXMLStreamReader(new FileReader("D://SmallXmltoSplit.xml"));

    streamReader.nextTag(); // Advance to next element
    streamReader.nextTag();
    streamReader.nextTag();
    streamReader.nextTag();
    streamReader.nextTag();
    streamReader.nextTag();

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = tf.newTransformer();
    String deptId = null;
    File file = new File("D://test" + ".xml");
    while (streamReader.hasNext()) {
        if (streamReader.isStartElement()) {
            if (streamReader.getLocalName().equals("deptId")) {
                if (deptId == null) {
                    deptId = streamReader.getElementText();
                    file = new File("D://" + deptId + ".xml");
                    t.transform(new StAXSource(streamReader), new StreamResult(file));
                } else if (deptId != streamReader.getElementText()) {
                    file = new File("D://" + deptId + ".xml");
                    t.transform(new StAXSource(streamReader), new StreamResult(file));
                } 
            }
            t.transform(new StAXSource(streamReader), new StreamResult(file));
        }
        streamReader.next();
    }
}

}

2 个答案:

答案 0 :(得分:1)

XML读取应按<row>进行,或多或少如下:

    XMLInputFactory xif = XMLInputFactory.newInstance();
    // Do not use a Reader, especially not a FileReader. An InputStream leaves the
    // encoding of the XML to the XMLStreamReader.
    InputStream in = Files.newInputStream(Paths.get("D:/SmallXmltoSplit.xml"));
    XMLStreamReader streamReader = xif.createXMLStreamReader(in);
    streamReader.nextTag();

    String id = "";
    String name = "";
    String deptId = "";

    String oldDeptId = null;

// File file = new File(“ D:/ test” +“ .xml”);

    while (streamReader.hasNext()) {
        if (streamReader.isStartElement()) {
            switch (streamReader.getLocalName()) {
            case "row":
                id = "";
                name = "";
                deptId = "";
                break;
            case "id":
                id = streamReader.getElementText();
                break;
            case "name":
                name = streamReader.getElementText();
                break;
            case "deptId":
                deptId = streamReader.getElementText();
                break;
            }
        }
        if (streamReader.isEndElement()) {
            switch (streamReader.getLocalName()) {
            case "START":
                if (oldDeptId != null) {
                    saveDept();
                    //oldDeptId = deptId;
                }
                break;
            case "row":
                if (!deptId.equals(oldDeptId)) {
                    if (oldDeptId != null) {
                        saveDept();
                        oldDeptId = deptId;
                    }
                    startDept(deptId);
                }
                appendDeptRow(id, name, deptId);
                break;
            }
        }
    }

写作无需变换即可完成;实际上,它可以作为文本来完成。

我把它留做练习。

不应使用FileReader和FileWriter,因为它们使用默认平台编码对字节进行编码。类Files具有许多不错的文件功能。

这里的另一个特色是UTF-16编码,它使几乎ASCII文件的大小增加了一倍。如您所提到的,文件很大,最好将文件保存为UTF-8,即使名称使用波斯语,希腊语,日语或保加利亚语也是如此。

答案 1 :(得分:1)

使用XSLT 2.0更容易做到这一点:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform version="2.0">
  <xsl:template match="/">
    <xsl:for-each-group select="//row" group-adjacent="deptId">
      <xsl:result-document href="{current-grouping-key()}.xml">
        <ABC>
         <END />
          <Tables>
           <START>
            <xsl:copy-of select="current-group()"/>
           </START>
          </Tables>
        </ABC>
      </xsl:result-document>
    </xsl:for-each-group>
  </xsl:template>
</xsl:transform>

要从Java应用程序运行此程序,您将需要下载Saxon,然后使用以下逻辑例如对其进行调用:

    Processor proc = new Processor(false);
    XsltCompiler comp = proc.newXsltCompiler();
    XsltExecutable exp = comp.compile(new StreamSource(new File("my-stylesheet.xsl")));
    Serializer out = proc.newSerializer(new File("output.xml"));
    Xslt30Transformer trans = exp.load30();
    trans.applyTemplates(new StreamSource(new File("input.xml"), out);

此处有更多详细信息:http://www.saxonica.com/documentation/index.html#!using-xsl/embedding/s9api-transformation