2016-08-09 78 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