2014-11-14 54 views
1


我需要搜索某些属性的XML并在发现该属性时删除其节点。例如,我想删除这与开始的属性书节点“#false”如果某个属性具有特定值,则删除XML节点

<catalog> 
    <book id="bk101" available="#false"> 
     <author>Gambardella, Matthew</author> 
     <title>XML Developer's Guide</title> 
     <genre>Computer</genre> 
     <price>44.95</price> 
     <publish_date>2000-10-01</publish_date> 
     <description>An in-depth look at creating applications 
     with XML.</description> 
    </book> 
</catalog> 

到目前为止,我已经能够捕获所有“#false”使用XPath表达式的元素:

String search = "//@*[starts-with(.,'#false')]"; 
NodeList nodeList = (NodeList) xPath. 
       compile(search).evaluate(doc, XPathConstants.NODESET); 

((Node)nodeList.item(0)).getParent(); // NULL!! 

但问题是“可用”元素的父节点为空,所以我找不到一种方法来删除整个“书籍”节点。任何帮助?

回答

1

的属性,使用Attr#getOwnerElement()检索包含该属性的元素:

NodeList nodeList = (NodeList) xPath. 
      compile(search).evaluate(doc, XPathConstants.NODESET); 

Node attrNode = nodeList.item(0); 
if(attrNode.getNodeType() == Node.ATTRIBUTE_NODE) { 
    Attr attr = (Attr) attrNode; 

    Element bookElement = attr.getOwnerElement(); 
    ... 
} 
+0

谢谢!正是我在找什么! – user2824073 2014-11-14 13:55:03

1

您可以使用此XPath ..这将匹配与书元素本身

//*[@*[starts-with(.,'#false')]] 

我希望这会帮帮我!

相关问题