使用Java从XML文件中删除与属性名称匹配的所有xml属性? [英] Using Java to remove all xml attributes from a XML file that match a attribute-name?

查看:73
本文介绍了使用Java从XML文件中删除与属性名称匹配的所有xml属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java从XML文件中删除与属性名称匹配的所有xml属性。我被困在这一点上。在这段代码的底部,我可以在循环时获取每个节点的属性值,但我无法弄清楚如何从Node中完全删除该属性。有什么想法吗?

I am trying to use Java to remove all xml attributes from a XML file that match a attribute-name. I am stuck at this point. At the bottom of this code I am able to get the attribute value of each node as I loop through but I can't figure out how to delete the attribute from the Node altogether . Any ideas?

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;
import org.xml.sax.SAXException;


public class StripAttribute { 

  public static void main(String[] args) { 

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    factory.setNamespaceAware(true); 
    org.w3c.dom.Document doc = null;
    NodeList nodes = null;
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      doc = db.parse("a.xml");
      nodes = doc.getChildNodes();
    }  catch (IOException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    }
    for ( int i = 0; i < nodes.getLength(); i++ ) { 
      String id = nodes.item(i).getNodeValue();
      if ( id.equals("siteKey")) {
        Element el = ((Attr) nodes.item(i)).getOwnerElement(); 
        el.removeAttribute(id);
      }
    } 

    Transformer transformer;
    StreamResult result = null;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      result = new StreamResult(new StringWriter()); 
      DOMSource source = new DOMSource(doc); 
      transformer.transform(source, result); 
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } 
    String xmlString = result.getWriter().toString(); 
    System.out.println(xmlString); 
  } 
}    

以下是我要转换的XML示例:

Here is a sample of the XML I want to transform:

https://gist.github.com/2784907

推荐答案

尝试:

for ( int i = 0; i < nodes.getLength(); i++ ) { 
    String id = nodes.item(i).getNodeValue();
    if ( id.equals("siteKey")) {
        //doc.removeChild(nodes.item(i));
        Element el = ((Attr) nodes.item(i)).getOwnerElement(); 
        el.removeAttribute(id);
    }
} 

查询返回的节点似乎已分离从文档中,所以getParentNode为null。 - 不,他们没有分离,我更新了代码。

It seems that the nodes returned by the query are detached from the document so getParentNode is null. - no, they are not detached, I updated the code.

我发现文章,表示 XPathExpression 返回的节点仍附加到文档。

I found an article that says that the nodes returned by XPathExpression are still attached to the document.

您是原始代码+上述更改:

You're original code + the above change:

public static void main(String[] args) throws Exception {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    Document doc = null;
    NodeList nodes = null;
    Set<String> ids = null;
    try {
        doc = factory.newDocumentBuilder().parse(new File("d:/a.xml"));

        XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//@siteKey");
        ids = new HashSet<String>();
        nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < nodes.getLength(); i++) {
        String id = nodes.item(i).getNodeValue();
        if (id.equals("siteKey")) {
            Element el = ((Attr) nodes.item(i)).getOwnerElement();
            el.removeAttribute(id);
        }
    }

    int dupes = 0;
    for (int i = 0; i < nodes.getLength(); i++) {
        String id = nodes.item(i).getNodeValue();
        if (ids.contains(id)) {
            System.out.format("%s is duplicate\n\n", id);
            dupes++;
        } else {
            ids.add(id);
        }
    }

    System.out.format("Total ids = %d\n Total Duplicates = %d\n", ids.size(), dupes);

    Transformer transformer;
    StreamResult result = null;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(doc);
        transformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    String xmlString = result.getWriter().toString();
    System.out.println(xmlString);

} 

更新:

for (int i = 0; i < nodes.getLength(); i++) {
    String id = nodes.item(i).getNodeValue();
    Element el = ((Attr) nodes.item(i)).getOwnerElement();
    el.removeAttribute(id);
}

这篇关于使用Java从XML文件中删除与属性名称匹配的所有xml属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆