1) Create XML Builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
2) Create XML Document
File f = ...;
Document doc = builder.parse(f);
URL u = ...;
Document doc2 = builder.parse(u);
InputStream in = ...;
Document doc3 = builder.parse(in);
3) Get Root Element
Document doc = ...;
Element root = doc.getDocumentElement();
String name = root.getTagName();
4) Iterate Children of Element
Element element = ...;
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instance of Element) {
Element childElement = (Element) child;
...
}
}
5) Iterate (Alternative) Children of Element
Element element = ...;
for (
Node childNode = element.getFirstChild();
childNode != null;
childNode = childNode.getNextSibling()
) {
if (childNode instance of Element) {
Element childElement = (Element) childNode;
...
}
}
6) Get Data from Text Node
Node child = ...;
if (child instanceof Text) {
Text textNode = (Text) child;
String text = textNode.getData().trim();
if (childElement.getTagName().equals("name")) {
name = text;
}
else if (childElement.getTagName().equals("size")) {
size = Integer.parseInt(text);
}
}
7) Iterate Atributes of Node
Element element = ...;
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node attributeNode = attributes.item(i);
String name = attribute.getNodeName();
String value = attribute.getNodeValue();
}
8) Get Attribute by Name
Element element = ...;
String unit = element.getAttribute("unit");
PS: See Also: (XmlDomViewer Sample Source)
DomTreeCellRenderer.java
DomTreeFrame.java
DomTreeModel.java
XmlDomViewer.java
%%
No comments:
Post a Comment