gpt4 book ai didi

java - 通过使用 xpath 获取同级值来查找 xml 节点值

转载 作者:行者123 更新时间:2023-11-30 07:43:50 26 4
gpt4 key购买 nike

我有以下 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=YesenumMapping 属性 dsrName= yesno 使用 xpath。如果我使用

则会出现错误
XPathExpression expr = xpath.compile("mappings/enumMapping[@dsrName=\""+dsrName+"\"]/valueMap//[dsrValue/text()=\""+dsrValue+"\"]/emValue");

最佳答案

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

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

说明:

  • /mappings :定位根元素mappings
  • /enumMapping[@dsrName='yesno'] :从根元素中查找子元素 enumMapping,其中 dsrName 属性值等于“是的”
  • /valueMap[dsrValue='Yes'] :从这样的 enumMapping 中,找到子元素 valueMap 其中 dsrValue 子元素等于"is"
  • /emValue :从这样的 valueMap 返回子元素 emValue

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

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

关于java - 通过使用 xpath 获取同级值来查找 xml 节点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34223770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com