用兄弟姐妹定位节点 : DOM编辑 « XML « Java 教程

En
Java 教程
1. 语言基础
2. 数据类型
3. 操作符
4. 流程控制
5. 类定义
6. 开发相关
7. 反射
8. 正则表达式
9. 集合
10. 线
11. 文件
12. 泛型
13. 本土化
14. Swing
15. Swing事件
16. 二维图形
17. SWT
18. SWT 二维图形
19. 网络
20. 数据库
21. Hibernate
22. JPA
23. JSP
24. JSTL
25. Servlet
26. Web服务SOA
27. EJB3
28. Spring
29. PDF
30. 电子邮件
31. 基于J2ME
32. J2EE应用
33. XML
34. 设计模式
35. 日志
36. 安全
37. Apache工具
38. 蚂蚁编译
39. JUnit单元测试
Java
Java 教程 » XML » DOM编辑 
33. 3. 5. 用兄弟姐妹定位节点
/*
Code revised from
Java, XML, and JAXP by Arthur Griffith John Wiley & Sons 2002

*/


import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class DOMEdit {
  static public void main(String[] arg) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringElementContentWhitespace(true);

    Document doc = null;
    try {
      DocumentBuilder builder = dbf.newDocumentBuilder();
      builder.setErrorHandler(new MyErrorHandler());
      InputSource is = new InputSource("personWithDTD.xml");
      doc = builder.parse(is);

      newEmail(doc, "B D""newEmail");

      write(doc);
    catch (Exception e) {
      System.err.println(e);
    }
  }

  public static void newEmail(Document doc, String newname, String newemail) {
    Element root = doc.getDocumentElement();
    Element person = (Elementroot.getFirstChild();
    while (person != null) {
      Element name = (Elementperson.getFirstChild();
      Text nametext = (Textname.getFirstChild();
      String oldname = nametext.getData();
      if (oldname.equals(newname)) {
        Element email = (Elementname.getNextSibling();
        Text emailtext = (Textemail.getFirstChild();
        emailtext.setData(newemail);
      }
      person = (Elementperson.getNextSibling();
    }
  }

  private static final String TAB = "    ";

  private static void write(Document docthrows IOException {
    outputHeading(doc);
    outputElement(doc.getDocumentElement()"");
  }

  private static void outputHeading(Document doc) {
    System.out.print("<?xml version=\"1.0\"");
    DocumentType doctype = doc.getDoctype();
    if (doctype != null) {
      if ((doctype.getPublicId() == null&& (doctype.getSystemId() == null)) {
        System.out.println(" standalone=\"yes\"?>");
      else {
        System.out.println(" standalone=\"no\"?>");
      }
    else {
      System.out.println("?>");
    }
  }

  private static void outputElement(Element node, String indent) {
    System.out.print(indent + "<" + node.getTagName());
    NamedNodeMap nm = node.getAttributes();
    for (int i = 0; i < nm.getLength(); i++) {
      Attr attr = (Attrnm.item(i);
      System.out.print(" " + attr.getName() "=\"" + attr.getValue() "\"");
    }
    System.out.println(">");
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++)
      outputloop(list.item(i), indent + TAB);
    System.out.println(indent + "</" + node.getTagName() ">");
  }

  private static void outputText(Text node, String indent) {
    System.out.println(indent + node.getData());
  }

  private static void outputCDATASection(CDATASection node, String indent) {
    System.out.println(indent + node.getData());
  }

  private static void outputComment(Comment node, String indent) {
    System.out.println(indent + "<!-- " + node.getData() " -->");
  }

  private static void outputProcessingInstructionNode(ProcessingInstruction node, String indent) {
    System.out.println(indent + "<?" + node.getTarget() " " + node.getData() "?>");
  }

  private static void outputloop(Node node, String indent) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
      outputElement((Elementnode, indent);
      break;
    case Node.TEXT_NODE:
      outputText((Textnode, indent);
      break;
    case Node.CDATA_SECTION_NODE:
      outputCDATASection((CDATASectionnode, indent);
      break;
    case Node.COMMENT_NODE:
      outputComment((Commentnode, indent);
      break;
    case Node.PROCESSING_INSTRUCTION_NODE:
      outputProcessingInstructionNode((ProcessingInstructionnode, indent);
      break;
    default:
      System.out.println("Unknown node type: " + node.getNodeType());
      break;
    }
  }
}

class MyErrorHandler implements ErrorHandler {
  public void warning(SAXParseException ethrows SAXException {
    show("Warning", e);
    throw (e);
  }

  public void error(SAXParseException ethrows SAXException {
    show("Error", e);
    throw (e);
  }

  public void fatalError(SAXParseException ethrows SAXException {
    show("Fatal Error", e);
    throw (e);
  }

  private void show(String type, SAXParseException e) {
    System.out.println(type + ": " + e.getMessage());
    System.out.println("Line " + e.getLineNumber() " Column " + e.getColumnNumber());
    System.out.println("System ID: " + e.getSystemId());
  }
}

//File: personWithDTD.xml
<?xml version="1.0" standalone="yes"?>

<!-- This document is both well formed and valid -->

<!DOCTYPE folks [
<!ELEMENT folks (person)*>
<!ELEMENT person (name, phone, email)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
<!ELEMENT email (#PCDATA)>
]>

<folks>
    <person>
        <name>B D</name>
        <phone>999 555-8888</phone>
        <email>b@xyz.net</email>
    </person>
</folks>
<?xml version="1.0" standalone="yes"?>
<folks>
    <person>
        <name>
            B D
        </name>
        <phone>
            newEmail
        </phone>
        <email>
            b@xyz.net
        </email>
    </person>
</folks>
33. 3. DOM编辑
33. 3. 1. 创建一个XML文档DOM树
33. 3. 2. 增加到列表
33. 3. 3. 插入一个新条目
33. 3. 4. 定位节点和修改文字
33. 3. 5. 用兄弟姐妹定位节点
33. 3. 6. 删除树节点
33. 3. 7. Replacing a Tree Node: Replacing an Existing Node with a New One
33. 3. 8. 定位元素标记名称
33. 3. 9. 树重复的部分
33. 3. 10. 设置属性
33. 3. 11. 删除属性
33. 3. 12. 移动和复制属性
33. 3. 13. 定位节点的ID
33. 3. 14. 编辑文本节点
33. 3. 15. 修改文字剪贴
33. 3. 16. 编辑文字插入和替换
33. 3. 17. 插入CDATASection节点
33. 3. 18. 正常化的所有文字
33. 3. 19. Moving Nodes between Documents: Copy a Node from One Parse Tree into Another
33. 3. 20. Editing by Using a Document Fragment: Creating a DocumentFragment Subtree and Appending to the Document
33. 3. 21. 插入处理指令和评论
33. 3. 22. 插入处理指令和评论方法
33. 3. 23. 一个DOM元素名称更改
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.