通过使用xpath获取其兄弟值来查找xml节点值

时间:2015-12-11 12:36:55

标签: java xml xpath

我有以下xml文件

<?xml version="1.0"?>
<mappings>
    <enumMapping id="1" dsrName="yesno" emName="yesno_t">
        <valueMap>
            <dsrValue>Yes</dsrValue>
            <emValue>1</emValue>
        </valueMap>
        <valueMap>
            <dsrValue>No</dsrValue>
            <emValue>2</emValue>
        </valueMap>

    </enumMapping>
    <enumMapping id="2" dsrName="altRoutingOnConFailure" emName="Alternate_Routing_On_Connection_Failure_t">
        <valueMap>
            <dsrValue>Same Peer</dsrValue>
            <emValue>1</emValue>
        </valueMap>
        <valueMap>
            <dsrValue>Different Peer</dsrValue>
            <emValue>2</emValue>
        </valueMap>
        <valueMap>
            <dsrValue>Same Connection</dsrValue>
            <emValue>3</emValue>
        </valueMap>
    </enumMapping>
</mappings>

和Java代码

public class Parser {
    Document doc;
    public Parser(String filename)
    {
        try{
            File inputFile = new File(filename);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            doc = dBuilder.parse(inputFile);
            doc.getDocumentElement().normalize();
            }catch(Exception e)
            {
                e.printStackTrace();
            }

    }

    public void searchDsrEnum(String dsrName,String dsrValue)
    {

          XPathFactory xPathfactory = XPathFactory.newInstance();
          XPath xpath = xPathfactory.newXPath();
          try {
            XPathExpression expr = xpath.compile("mappings/enumMapping[@dsrName=\""+dsrName+"\"]/valueMap/dsrValue");
            NodeList n1=(NodeList)expr.evaluate(doc,XPathConstants.NODESET);
            System.out.println(n1.getLength());


            //System.out.println(n1.);

        } catch (XPathExpressionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}

我需要使用emValue找到dsrValue字段,Yes = enumMappingdsrName=yesno属性xpath。 如果我使用

,我会收到错误
XPathExpression expr = xpath.compile("mappings/enumMapping[@dsrName=\""+dsrName+"\"]/valueMap//[dsrValue/text()=\""+dsrValue+"\"]/emValue");

1 个答案:

答案 0 :(得分:1)

这是一个可能的XPath表达式:

/mappings/enumMapping[@dsrName='yesno']/valueMap[dsrValue='Yes']/emValue

解释:

  • /mappings:找到根元素mappings
  • /enumMapping[@dsrName='yesno']:从根元素中找到子元素enumMapping,其中dsrName属性值等于"yesno"
  • /valueMap[dsrValue='Yes']:来自此类enumMapping,找到子元素valueMap,其中dsrValue子元素等于"Yes"
  • /emValue:来自此valueMap返回子元素emValue

我还建议使用单引号和String.Format()来清理代码:

String query = "/mappings/enumMapping[@dsrName='%s']/valueMap[dsrValue='%s']/emValue";
XPathExpression expr = xpath.compile(String.Format(query, dsrName, dsrValue));