Reputation: 15406
I would like to parse an XML document and change the attribute names to lowercase using JDOM.
For example, I would like the following:
<record ID="1" name="Dom" />
<record iD="2" nAmE="Bob" />
To become:
<record id="1" name="Dom" />
<record id="2" name="Bob" />
What is the best way to achieve this?
Upvotes: 0
Views: 248
Reputation: 17707
Using JDOM 2.0.2 you could probably use an XPath, and loop the names. The problem is that you could end up with a conflict if, for example, an Element has multiple attributes that resolve to the same lower-case names, like 'ID' and 'id'.... but that is something you probably won't have to deal with.
Try some code like (will only return attributes in the no-namespace namespace):
XPathExpression<Attribute> xp = XPathFactory.instance().compile("//@*", Filters.attribute());
for (Attribute a : xp.evaluate(mydoc)) {
a.setName(a.getName().toLowerCase());
}
If you do not want to use XPaths (this way is also probably faster), you can loop the descendants:
for (Element e : mydoc.getDescendants(Filters.element())) {
if (e.hasAttributes()) {
for (Attribute a : e.getAttributes()) {
a.setName(a.getName().toLowerCase());
}
}
}
Rolf
Upvotes: 0