VTD XML解析新手求助:如何获取指定属性的<child>标签值?
如何用VTD-XML直接获取指定属性的标签值?
作为VTD新手,我不想使用DOM或SAX对XML进行全量解析,希望直接获取属性child_id为"1_2"的
标签的值,我的XML结构如下: <?xml version="1.0" encoding="UTF-8"?><test:mark><parent parent_id="1"><child child_id="1_1">11Value</child><child child_id="1_2">12Value</child><child child_id="1_3">13Value</child></parent><other other_id="1"><inner>1233</inner></other></test:mark>
没问题,VTD-XML就是为这种高效精准的XML查询场景设计的——完全不用像DOM那样加载整个文档树,基于指针的解析方式加上XPath支持,能快速定位到你要的节点。下面是具体的实现方案:
核心思路
借助VTD-XML的AutoPilot工具,通过XPath表达式直接过滤出child_id="1_2"的<child>节点,再提取它的文本值,全程内存占用低,操作效率高。
完整代码示例
import com.ximpleware.*; public class VTDXmlQueryDemo { public static void main(String[] args) throws VTDException { // 你的原始XML字符串 String xmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><test:mark><parent parent_id=\"1\"><child child_id=\"1_1\">11Value</child><child child_id=\"1_2\">12Value</child><child child_id=\"1_3\">13Value</child></parent><other other_id=\"1\"><inner>1233</inner></other></test:mark>"; // 初始化VTD生成器 VTDGen vtdGenerator = new VTDGen(); vtdGenerator.setDoc(xmlContent.getBytes()); vtdGenerator.parse(false); // 关闭命名空间支持,若需处理命名空间可改为true并注册 // 获取XML导航器 VTDNav vtdNavigator = vtdGenerator.getNav(); // 创建AutoPilot执行XPath查询 AutoPilot autoPilot = new AutoPilot(vtdNavigator); // XPath规则:匹配所有child标签中child_id属性为1_2的节点 autoPilot.selectXPath("//child[@child_id='1_2']"); // 执行查询并处理结果 int nodeIndex = autoPilot.evalXPath(); if (nodeIndex != -1) { // 获取节点的文本内容索引 int textIndex = vtdNavigator.getText(); if (textIndex != -1) { // 转换为规范化字符串(自动处理多余空白) String targetValue = vtdNavigator.toNormalizedString(textIndex); System.out.println("目标值:" + targetValue); // 输出:12Value } } } }
重要细节说明
- 命名空间处理:你的XML里有
test:前缀,如果这个前缀绑定了具体的命名空间URI,需要开启命名空间支持并注册:vtdGenerator.parse(true); // 开启命名空间解析 autoPilot.declareXPathNameSpace("test", "http://your-namespace-uri.com"); // 对应的XPath也要调整为://test:mark/parent/child[@child_id='1_2'] - XPath优化:如果需要更精确的路径(比如限定在
<parent>下的<child>),可以把XPath改成/test:mark/parent/child[@child_id='1_2'],查询速度会更快。 - 内存优势:VTD-XML采用非侵入式解析,不会创建大量对象,内存占用仅为DOM的1/5左右,特别适合处理大XML文件的精准查询。
内容的提问来源于stack exchange,提问作者Abhaysinh Bhelke
相关产品推荐
相关产品推荐

