App下載
首頁(yè)javadomJava HTML/XML - 如何將值分配給XML節(jié)點(diǎn)

Java HTML/XML - 如何將值分配給XML節(jié)點(diǎn)

我們想知道如何將值分配給XML節(jié)點(diǎn)。
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
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.NodeList;
import org.xml.sax.InputSource;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance()
        .newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(
        "<emp><empname><firstName></firstName><lastName></lastName></empname></emp>")));
    NodeList customerNodes = doc.getElementsByTagName("empname");
    for (int i = 0; i < customerNodes.getLength(); i++) {
      NodeList children = customerNodes.item(i).getChildNodes();
      for (int j = 0; j < children.getLength(); j++) {
        String childNode = children.item(j).getNodeName();
        if (childNode.equalsIgnoreCase("firstName")) {
          children.item(j).setTextContent(String.valueOf("John"));
        } else if (childNode.equalsIgnoreCase("lastName")) {
          children.item(j).setTextContent(String.valueOf("Doe"));
        }
      }
    }
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    System.out.println(writer.getBuffer().toString());
  }
}