0

下面是我正在使用的 xml 文件的屏幕截图,我需要从标签扩展中获取值“switchboardid1”: XML 片段

以下是我编写的代码:我需要从扩展标签访问属性“switchboardid1”。我总是只得到 null 作为回报。请更正我的代码并帮助我理解。

我有 NamespaceContext 类来返回类“HardcodedNamespaceResolver”中的命名空间,它正确地返回了 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;
            }
    }


 }

}

4

1 回答 1

0

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 中心:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.4.0</version>
</dependency>
于 2018-06-23T09:05:23.500 回答