2016-08-09 81 views
0

我已经使用JAXB将我的XSD文件转换为JAVA对象。JAXB搜索和删除元素节点

我接下来要做的就是解析这些对象的xml文件。

现在我的目标是添加,删除,搜索XML中的一些节点。

我很难在JAXB中做到这一点。

例如我想要匹配属性名称=“weight”的任何节点。

如何在JAXB对象中执行此操作?

在DOM中,这种搜索/更新/删除非常简单。

我如何在JAXB中做到这一点?

或e.g

我有一个属性名称,以匹配“体重”,它是类型interfaceClass的。

<CAEXFile> 
<InterfaceCLASSLIB> 
<interfaceclass> 
<attribute name="weight> 
<../> 

所以为了访问接口类。我将不得不通过所有的对象层次结构。

CAEXFile --->获取InterfaceClassLib()---> getInterfaceClass() - > gettAttributes();

注意每个get方法都会返回一个Array列表,因为可以有很多接口类,属性为e.t.c。

然后这是一个非常昂贵的方法。

我没有找到任何预定义的函数来达到特定的节点。

任何帮助,将不胜感激。应该将DOM-XML转换为xml插入删除更新。

回答

1

正如你所说的使用JAXB搜索节点很贵。我会使用XPathFactory作为标准Java的一部分来获取所需的节点。 象下面这样:

public static void main(String[] args) throws Exception 
{ 
    XPathFactory xpf = XPathFactory.newInstance(); 
    XPath xpath = xpf.newXPath(); 

    InputSource xml = new InputSource("<your_path_to_input.xml>"); 
    Object result = (Object) xpath.evaluate("//attribute[@name=\"weight\"]", xml, XPathConstants.NODESET); 
    if (result != null && result instanceof NodeList) 
    { 
     NodeList nodeList = (NodeList)result; 
     if (nodeList.getLength() > 0) 
     { 
     for (int i = 0; i < nodeList.getLength(); i++) 
     { 
      org.w3c.dom.Node node = nodeList.item(i); 
      System.out.println(node.getNodeValue()); 
     } 
     } 
    } 
} 

的XPath是//attribute[@name="weight"],它递归搜索XML为attribute节点已属性称为name与值weight