The javax.xml.parsers.DocumentBuilder seems to be sorting attributes by name automatically. I would like to get the attributes in the order that they appear in the XML file, not sorted. Is there any way to turn off this sorting behavior? Here's a snippet that shows what I'm doing:
// Here is my parse() method that creates a new DocumentBuilder and parses it to a Document.
public void parse(File file) throws IOException, ParserConfigurationException, SAXException {
InputStream is = new FileInputStream(file);
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(new InputSource(is));
try {
parse(doc);
fileName = file.toString();
} finally {
is.close();
}
}
// This starts recursion to build nodes for all elements in the Document.
public void parse(Document doc) {
Element docRoot = doc.getDocumentElement();
rootElement = new XMLElement(this, docRoot);
buildNodesFor(docRoot, rootElement);
addNode(rootElement);
}
// Recursively build descendants for each Element
private void buildNodesFor(Node node, XMLNode xmlNode) {
NodeList nodes = node.getChildNodes();
for (int i = 0; i < nodes.getLength(); ++i) {
Node tmpNode = nodes.item(i);
switch (tmpNode.getNodeType()) {
case Node.ELEMENT_NODE: {
Element tmpElement = (Element)tmpNode;
// XMLElement constructor iterates over the attribute list.
XMLElement newNode = new XMLElement(xmlNode, tmpElement);
xmlNode.addNode(newNode);
buildNodesFor(tmpElement, newNode);
break;
}
case Node.COMMENT_NODE: {
break;
}
case Node.TEXT_NODE: {
break;
}
default: {
System.out.println("unrecognized Node: "+tmpNode+", node type: "+tmpNode.getNodeType());
}
}
}
}
// Here is the XMLElement constructor that iterates over the attributes in the order given by the Document:
public XMLElement(XMLNode parent, Element element) {
super(parent, element.getNodeName(), "");
NamedNodeMap nnm = element.getAttributes();
for (int i = 0; nnm != null && i < nnm.getLength(); ++i) {
Node nd = nnm.item(i);
addAttribute(new XMLAttribute(this, nd));
}
}
This is not an SSCCE because I just want to show that I'm iterating over the Attributes in the same order that the Document gave them to me. The attributes are always sorted by name (I'm guessing so it can later do a binary search) but I would like to turn this behavior off and get the attributes in the order they appear in the file, not in sort order. Is there any way to do this?
Thanks!
Edited by: BinaryDigit on Apr 7, 2008 4:11 PM
Tried to add Dukes but don't see how...