java对xml节点属性的添加和删除

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class domTest3 {

 public static void main(String[] args) throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.parse(new File("src/shuiguo.xml"));

  createAttribute(doc);
  removeAttribute(doc);
 }

 public static void removeAttribute(Document doc) throws Exception {
  Node apple = doc.getElementsByTagName("苹果").item(0);

  apple.getAttributes().removeNamedItem("id");

  TransformerFactory factory = TransformerFactory.newInstance();
  Transformer former = factory.newTransformer();
  former.transform(new DOMSource(doc), new StreamResult(new File(
    "src/shuiguo.xml")));

 }

 public static void createAttribute(Document doc) throws Exception {
  Node orange = doc.getElementsByTagName("桔子").item(0);
  if (orange.getNodeType() == Node.ELEMENT_NODE) {
   Element element = (Element) orange;
   element.setAttribute("id", "333");

   TransformerFactory factory = TransformerFactory.newInstance();
   Transformer former = factory.newTransformer();
   former.transform(new DOMSource(doc), new StreamResult(new File(
     "src/shuiguo.xml")));
  }
 }
}

你可能感兴趣的:(xml)