Java Tutorial/XML/CDATA

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Accessing character data (CDATA) of XML element

import java.util.Stack;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class Main extends DefaultHandler {
  private Stack currentElement = new Stack();
  public void startElement(String uri, String localName, String qName, Attributes attrs)
      throws SAXException {
    currentElement.push(qName);
  }
  public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement.pop();
  }
  public void characters(char[] ch, int start, int length) throws SAXException {
    String cdata = new String(ch, start, length);
    System.out.println("Element "" + currentElement.peek() + "" contains text: " + cdata);
  }
  public static void main(String[] args) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    SAXParser parser = factory.newSAXParser();
    parser.parse("sample.xml", new Main());
  }
}





Adding a CDATA Section to a DOM Document

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    // Add a CDATA section to the root element
    element = doc.getDocumentElement();
    CDATASection cdata = doc.createCDATASection("data");
    element.appendChild(cdata);
  }
}





Append and insert data to CharacterData

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    CDATASection cdataNode = doc.createCDATASection("");
    Comment commentNode = doc.createComment("");
    Text textNode = doc.createTextNode("");
    // All three types of nodes implement the CharacterData interface
    CharacterData cdata = cdataNode;
    cdata = commentNode;
    cdata = textNode;
    // data
    int offset = 5;
    cdata.insertData(offset, "a "); 
    cdata.appendData(" b"); 
  }
}





Converting CDATA Nodes into Text Nodes While Parsing an XML File

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class Main {
  public static void main(String[] argv) throws Exception{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setCoalescing(true);
    Document doc = factory.newDocumentBuilder().parse(new File("infilename.xml"));
    // doc will not contain any CDATA nodes
  }
}





Delete data from CharacterData

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    CDATASection cdataNode = doc.createCDATASection("");
    Comment commentNode = doc.createComment("");
    Text textNode = doc.createTextNode("");
    // All three types of nodes implement the CharacterData interface
    CharacterData cdata = cdataNode;
    cdata = commentNode;
    cdata = textNode;
    // Delete text
    int offset = 0;
    int len = 5;
    cdata.deleteData(offset, len); 
  }
}





Get character data (CDATA) from xml document

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("data.xml");
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(file);
    NodeList nodes = doc.getElementsByTagName("topic");
    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);
      NodeList title = element.getElementsByTagName("title");
      Element line = (Element) title.item(0);
      System.out.println("Title: " + getCharacterDataFromElement(line));
    }
  }
  public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
      CharacterData cd = (CharacterData) child;
      return cd.getData();
    }
    return "";
  }
}





Get substring from CharacterData

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    CDATASection cdataNode = doc.createCDATASection("");
    Comment commentNode = doc.createComment("");
    Text textNode = doc.createTextNode("");
    // All three types of nodes implement the CharacterData interface
    CharacterData cdata = cdataNode;
    cdata = commentNode;
    cdata = textNode;
    cdata.setData("some data");
    int len = cdata.getLength();
    int offset = 5;
    len = 4;
    String s = cdata.substringData(offset, len);
  }
}





Replace Data in CharacterData

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    CDATASection cdataNode = doc.createCDATASection("");
    Comment commentNode = doc.createComment("");
    Text textNode = doc.createTextNode("");
    // All three types of nodes implement the CharacterData interface
    CharacterData cdata = cdataNode;
    cdata = commentNode;
    cdata = textNode;
    // Replace text
    String replacement = "c";
    int offset = 10;
    int len = 6;
    cdata.replaceData(offset, len, replacement);
  }
}





Set Data to Character Data

import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.rument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class Main {
  public static void main(String[] argv) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    CDATASection cdataNode = doc.createCDATASection("");
    Comment commentNode = doc.createComment("");
    Text textNode = doc.createTextNode("");
 
    CharacterData cdata = cdataNode;
    cdata = commentNode;
    cdata = textNode;
    cdata.setData("some data");
    int len = cdata.getLength();
  }
}