假设 blah url有以下xml,我想编写一个xpath表达式(或者如果你有其他想法来实现它),那么当输出“ graphics ”时值“ apple ”作为命令行参数提供,或者当 pfizer 作为命令行参数给出时,它输出 QA 。此外,我没有此特定xml的节点名称
<employers>
<company-name>apple</company-name>
<department>graphics</department>
<company-name>pfizer</company-name>
<department>QA</department>
</employers>
这是我到目前为止的尝试。请随意添加其他代码
public class Xpathparser{
public String parsing(){
String url="http://www.blahurl.com";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpathexpression?>);
String neededValue=expr.evaluate(expr); //not sure about this.
// code needed to display this
System.out.println(doc.toString());
}}
答案 0 :(得分:1)
给定一个分配了公司名称的Java String变量
String companyName = "apple";
您可以构造一个XPath表达式,
"//department[preceding-sibling::company-name = '" + companyName + "'][1]"
这将选择department
,其前一个兄弟姐妹的company-name
值由companyName
给出(假设您随附的Java Document*
和XPath*
设施是正确的。)