0
我需要使用XPath導航到分析/分析參數屬性通過添加一個新值:使用XPath添加一個新的價值屬性
作爲第一步,我試圖檢索來自分析標記的值,但無法使其正常工作(沒有檢索到樣本值,控制檯中沒有輸出)。任何人都可以看到我在哪裏錯了,然後進一步展示如何添加新的價值。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XPathTestReports {
public static void main(String[] args) {
try {
String xpath = "/UserDocument/report-plan-catalog/collection/collection/collection/report-config/report-plan/settings[@analysis]";
FileInputStream file = new FileInputStream(new File("c:/workspace/savedreportscatalog.xml"));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xPathExpression = xPath.compile(xpath);
String attributeValue = "" + xPathExpression.evaluate(xmlDocument, XPathConstants.STRING);
System.out.println(attributeValue);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
}
}
XML示例
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<UserDocument>
<report-plan-catalog>
<collection timestamp="" title="report plans" uid="">
<collection container-id="" timestamp="2015-04-29" title="*" uid="">
<collection container-id="94533" timestamp="2015-04-29" title="*" uid="5cfc">
<report-config container-id="5cfc" timestamp="2015-04-29" title="Asset" type="Risk" uid="4718">
<configuration>
<reportType>Live</reportType>
</configuration>
<report-plan name="Asset">
<columns>
<column name="Nom" subtotal-function="Sum" total-function="Sum"/>
<column name="Id"/>
<column name="Ref"/>
</columns>
<settings analysis="someValue" analysisParameters="" filtering-enabled="true" object-actions="false" show-object-actions="true" sorting-enabled="true"/>
<viewpoint kind="simple">
<slices/>
</report-plan>
</report-config>
</collection>
</collection>
</collection>
</report-plan-catalog>
</UserDocument>
@kjhughes謝謝,非常感謝。 –
是的你是正確的我想選擇設置元素的@analysis屬性。我已經改變了這個來匹配你的例子,但它仍然不打印system.out中的任何東西?我的最終目標是傳遞可能來自HashMap的值,但此刻我正在測試一個獨立的xml文件,以查看是否可以傳遞任何類型的值以使其首先工作。 – Kelv
你會期望''''打印出什麼?嘗試在你的XML中爲'analyze =「」'放置一個實際值。 – kjhughes