从 XML 快速检索数据

fast of retrieving data from XML

我有样品xml

<?xml version="1.0" encoding="UTF-8"?>
  <tag_1>
     <tag_2>A</tag_2>
     <tag_3>B</tag_3>
     <tag_4>C</tag_4>
     <tag_5>D</tag_5>
  </tag_1>
</xml>

现在我只想提取特定数据。

例如

tag_1/tag_5 -> D

tag_1/tag_5 是我的数据定义(我唯一想要的数据),它本质上是动态的,这意味着明天 tag_1/tag_4 将是我的数据定义。

所以实际上我的 xml 是一个大数据集。这些 xml 有效负载大约为 50,000/小时到 80,000/小时。

我想知道是否已经有高性能 xml reader 工具或一些我可以实现的特殊逻辑,它根据数据定义提取数据。

目前我有使用 Stax 解析器的实现,但它需要将近一天的时间来解析 80,000 个 xml。

public class VTDParser {

    private final Logger LOG = LoggerFactory.getLogger(VTDParser.class);

    private final VTDGen vg;

    public VTDParser() {
        vg = new VTDGen();
    }

    public String parse(final String data, final String xpath) {
        vg.setDoc(data.getBytes());
        try {
            vg.parse(true);
        } catch (final ParseException e) {
            LOG.error(e.toString());
        }

        final VTDNav vn = vg.getNav();
        final AutoPilot ap = new AutoPilot(vn);
        try {
            ap.selectXPath(xpath);
        } catch (final XPathParseException e) {
            LOG.error(e.toString());
        }

        try {
            while (ap.evalXPath() != -1) {
                final int val = vn.getText();
                if (val != -1) {
                    return vn.toNormalizedString(val);
                }
            }
        } catch (XPathEvalException | NavException e) {
            LOG.error(e.toString());
        }
        return null;
    }
}

这是我对您的代码的 mod,它编译 xpath 一次并重复使用多次。它在不绑定到 VTDNav 实例的情况下编译 xpath。它还会在退出解析方法之前调用 resetXPath。但是,我没有向您展示如何使用 VTD 对 xml 文档进行预索引......以避免重复解析......我怀疑它可能是为您的项目带来不同...这是关于 vtd-xml..

功能的论文参考

http://recipp.ipp.pt/bitstream/10400.22/1847/1/ART_BrunoOliveira_2013.pdf

import com.ximpleware.*;


public class VTDParser {
      // private final Logger LOG = LoggerFactory.getLogger(VTDParser.class);

        private final VTDGen vg;
        private final AutoPilot ap;
        public VTDParser() throws VTDException{
            vg = new VTDGen();
            ap = new AutoPilot();
            ap.selectXPath("/a/b/c");// this is how you compile xpath w/o binding to an XML doc
        }

        public String parse(final String data, final AutoPilot ap1) {
            vg.setDoc(data.getBytes());
            try {
                vg.parse(true);
            } catch (final ParseException e) {
                LOG.error(e.toString());
            }

            final VTDNav vn = vg.getNav();
            ap1.bind(vn);
            try {
                while (ap.evalXPath() != -1) {
                    final int val = vn.getText();
                    if (val != -1) {
                        return vn.toNormalizedString(val);
                    }
                }
            } catch (XPathEvalException | NavException e) {
                LOG.error(e.toString());
            }
            ap.resetXPath();// reset your xpath here
            return null;
        }
}