11/23/2007

Java XML parse

1. import
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.*
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;

2. generate
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse() //overloaded:
 parse(File f);
 parse(InputSource is);
 parse(InputStream is);
 parse(InputStream is, String systemId);
 parse(String uri);

3.get Element
 (1). Element getElementById(String elementId)
 (2). NodeList getElementsByTagName(String tagname)
 (3). NodeList getElementsByTagNameNS(String namespaceURI, String localName)

4. get Attribute
NamedNodeMap nnm = node.getAttributes();

5.get attribute name
nnm.item(i).getNodeName();

6.get attribute value
nnm.item(i).getNodeValue();

0 comments: