【问题标题】:Remove an XML Node if an attribute has a specific value如果属性具有特定值,则删除 XML 节点
【发布时间】:2014-11-14 12:47:15
【问题描述】:


我需要在 XML 中搜索某些属性,如果找到该属性,则删除其节点。例如,我想删除属性以“#false”开头的书节点

<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>

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

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

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

但是问题是“可用”元素的父节点为空,所以我找不到删除整个“书”节点的方法。有什么帮助吗?

【问题讨论】:

    标签: java xml dom xpath


    【解决方案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();
        ...
    }
    

    【讨论】:

    • 谢谢!正是我想要的!
    【解决方案2】:

    你可以使用这个 xpath .. 它将与 book 元素本身匹配

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

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多