即使在java中有名称空间管理,也无法从xml获取节点
下面是我正在处理的xml文件的屏幕截图,我需要从标记扩展名中获取值“switchboardid1”: 下面是我编写的代码:我需要从extensions标签访问属性“switchboardid1”。我得到的回报总是空的。请更正我的代码并帮助我理解 我有NamespaceContext类来返回类'HardcodedNamespaceResolver'中的名称空间,它正确地返回了nfh名称空间的值即使在java中有名称空间管理,也无法从xml获取节点,java,xml,xmlnodelist,Java,Xml,Xmlnodelist,下面是我正在处理的xml文件的屏幕截图,我需要从标记扩展名中获取值“switchboardid1”: 下面是我编写的代码:我需要从extensions标签访问属性“switchboardid1”。我得到的回报总是空的。请更正我的代码并帮助我理解 我有NamespaceContext类来返回类'HardcodedNamespaceResolver'中的名称空间,它正确地返回了nfh名称空间的值 public void test() throws Throwable { String x
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;
}
}
}
}SimpleXml可以做到:
final String yourxml = ...
final SimpleXml simple = new SimpleXml();
System.out.println(getSwitchBoardId(simple.fromXml(yourxml)));
private static String getSwitchBoardId(final Element element) {
return element.children.get(2).children.get(0).children.get(4).children.get(0).children.get(0).text;
}
将输出:
switchboardid1
来自maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>
com.github.codemontur
simplexml
1.4.0