XPATH 查询 select parent 根据匹配的子元素条件

XPATH query to select parent based on matching child element conditon

我正在尝试解析以下 xml 以根据特定条件获取 ScId 元素值。 xpath 字符串中提到了这种情况,然后 select xpathNext 字符串中的 ScId 值。

<?xml version="1.0" encoding="ISO-8859-1"?>
<SchoolData>
<School>
<ScId>SC101-91</ScId>
    <Location>
      <Branch>
        <BranchId>Br-111</BranchId>
        <Type>Residential</Type>
        <RealType>Residential</RealType>
      </Branch>
      <Branch>
        <BranchId>BR-222</BranchId>
        <Type>Daycare</Type>
        <RealType>Daycare</RealType>
      </Branch>
      <Branch>
        <BranchId>Br-333</BranchId>
        <Type>Unknown</Type>
        <RealType>Unknown</RealType>
      </Branch>
    </Location>
</School>

<School>
<ScId>RC101-92</ScId>
    <Location>
      <Branch>
        <BranchId>Br-111</BranchId>
        <Type>Residential</Type>
        <RealType>Residential</RealType>
      </Branch>
      <Branch>
        <BranchId>BR-222</BranchId>
        <Type>Daycare</Type>
        <RealType>Daycare</RealType>
      </Branch>
      <Branch>
        <BranchId>Br-333</BranchId>
        <Type>Unknown</Type>
        <RealType>Unknown</RealType>
      </Branch>
    </Location>
</School>
</SchoolData>

我正在使用 VTD xml 解析器使用嵌套的 xpath 查询来获取以 RC 和 Type = Daycare 开头的 ScId 值。

下面是代码

String xpath = "/*/School[starts-with(ScId,'RC')]/Location/Branch[Type='Daycare']";
        String xml = "/school.xml";
        
        final VTDGenHuge vg = new VTDGenHuge();
        System.out.println("Parsing");
        vg.parseFile(xml, true, VTDGenHuge.MEM_MAPPED);

        VTDNavHuge vn = vg.getNav();

        AutoPilotHuge aph = new AutoPilotHuge(vn);
        String xpathNext = "concat(//ScId,'-NEW')";
        aph.selectXPath(xpath);
        while ((aph.evalXPath()) != -1) {
            getparsedValue(vn,xpathNext);
            
        }

解析逻辑为

private static String getparsedValue(final VTDNavHuge vn, String xpath) throws NavException,

    XPathParseException, XPathEvalException, XPathParseExceptionHuge, XPathEvalExceptionHuge, NavExceptionHuge{

        String value = null;
        vn.push();
        
        AutoPilotHuge ap = new AutoPilotHuge(vn);
        ap.selectXPath(xpath);

        ap.bind(vn);
        value = ap.evalXPathToString();
        System.out.println("parsed value is " +value);
        vn.pop();
        return value;
    }

这个returns我

parsed value is SC101-91-NEW

虽然我期待它是

parsed value is RC101-92-NEW

也许这个 XPath-1.0 表达式对您有帮助。我没有 Java 可以测试它。

/*/School[starts-with(ScId,'RC') and Location/Branch[Type='Daycare']]

这会遍历所有 <School>个满足条件的元素。
要获得 <ScId>,请将字符串 /ScId 添加到表达式的末尾。