以下は、私が使用している xml ファイルのスクリーンショットです。タグ Extensions から値「switchboardid1」を取得する必要があります。
以下は私が書いたコードです: 拡張タグからプロパティ 'switchboardid1' にアクセスする必要があります。私は常に null のみを返します。私のコードを修正して、理解を助けてください。
クラス 'HardcodedNamespaceResolver' の名前空間を返す NamespaceContext クラスがあり、nfh 名前空間の値を正しく返しています。
public void test() throws Throwable
{
String xpath="//ElectricalProject/Equipments/Equipment/Extensions/Extension/nfh:extensionProperty[@name='switchboardId']";
Node node = GetNodeFromXml("PutNFInProj.xml",xpath);
Element ele = (Element) node;
System.out.println(ele.getNodeValue().toString());
}
//Function to GET a single Node from xml file wrt to xpath defined
public Node GetNodeFromXml(String XmlFileName, String xPathExpression) throws Throwable
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(GetDataFile(XmlFileName));
((org.w3c.dom.Document) doc).getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setNamespaceContext(new HardcodedNamespaceResolver());
NodeList nodeList = (NodeList) xPath.evaluate(xPathExpression,doc,XPathConstants.NODESET);
switch (nodeList.getLength())
{
case 0:
{
log.error("In Function: GetNodeFromXml - There are no nodes with respect to given xpath, Please Check the Xpath");
return null;
}
case 1:
{
Node nNode = nodeList.item(0);
return nNode;
}
default:
{
log.error("In Function: GetNodeFromXml- There are more than one nodes with respect to given xpath");
return null;
}
}
}
}