> Don't work directly with the Document - instead get the "root" Element
> with getDocumentElement() and work with that
>
> Bill
There is no getElementById(String) with the type Element.
We can only search by tagname. And I would like to search by Id
I define some attribute as ID in my DTD.
Thx.
Jean-Philippe Martin - 02 Mar 2004 23:42 GMT
In fact, with a parsed file wich contains elements, the methods works
fine, but if we add element (with id) to the Document then the methods
stucks...
You can try it.
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Test20040302 {
public static void main (String[] args) {
try {
DocumentBuilderFactory docBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder =
docBuilderFactory.newDocumentBuilder();
Document xmlDocument = docBuilder.parse(args[0]);
if (xmlDocument != null) {
Element god = xmlDocument.getElementById("Kibo");
if (god != null) {
System.out.println(god.getAttribute("home"));
}
else {
System.out.println("Element not found.");
}
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
Use it with a such file passe in argument
Code:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE gods [
<!ELEMENT gods (god)+>
<!ELEMENT god empty>
<!ATTLIST god
name ID #REQUIRED
home CDATA #implied>
]>
<gods>
<god name="Kibo" home="http://www.kibo.com/" />
<god name="Xibo" />
</gods>
Then add a node after "Element god =
xmlDocument.getElementById("Kibo"); "
with this method. You won't be able to search for Butch with the same
method after.
Code:
static void addNode(Document doc) {
Element elem = doc.createElement("god");
elem.setAttribute("home", "GamerZ");
elem.setAttribute("name", "Butch");
((Element)
doc.getElementsByTagName("gods").item(0)).appendChild(elem);
}