最近用DOM4j实现了对XML的解析,遍历XML element, 增加declare namespace, 设置XML standalone="yes", 和写入XML等操作的操作:
(1) 遍历XML element和每个element attributes:
首先获取XML document的root element节点后,然后定义一个递归调用的方法,来实现XML element的遍历:
private void traverseElement(Element element,StringBuffer strbuf) throws DocumentException{
StringBuffer interbuf = new StringBuffer(strbuf);
StringBuffer interbuf2 = new StringBuffer(strbuf);
for (Iterator j = element.elementIterator(); j.hasNext();) { //通过调用elementIterator()方法实现对child element遍历
Element obj = (Element) j.next();
System.out.println(interbuf.toString()+obj.getName());
for ( Iterator i = obj.attributeIterator(); i.hasNext(); ) { //遍历element的attribute
Attribute attribute = (Attribute) i.next();
System.out.print(" 元素的属性名和值:"+attribute.getName()+"="+attribute.getStringValue());
}
if(obj.attributeCount()>0) System.out.println("");
if(getElementChild(obj)) {
traverseElement(obj,new StringBuffer(interbuf2.append("--")));
interbuf2.setLength(interbuf2.length()-2);
}
}
}
(2) 增加declare namespace:
首先要获取XML中已经声明的namespace, 这些namespace的prfix可能是ns2, ns3, ns4...等等
List declareNamespaces = rootElm.declaredNamespaces(); //获取XML document已经声明的namespace
for (Namespace ns: declareNamespaces){
System.out.println("namespace prefix:"+ ns.getPrefix()+", namespace URI:"+ns.getURI());
}
int nslen = root.declaredNamespaces().size() + 1;
nsPrefix = "ns" + nslen;
root.addNamespace(nsPrefix, GEN_CDRNS); //root: rootelement, nsPrefix:XML namespace前缀, GEN_CDRNS: 新增namespace的URI
在dom4j中不支持直接在outputFormat中设置standalone属性的方法,可以用过改写XMLWriter中的writeDeclaration()方法来实现:
public class StandaloneWriter extends XMLWriter {
public StandaloneWriter(OutputStream out, OutputFormat format)
throws UnsupportedEncodingException
{
super(out,format);
}
protected void writeDeclaration()
throws IOException
{
OutputFormat format = getOutputFormat();
String encoding = format.getEncoding();
if(!format.isSuppressDeclaration())
{
writer.write("");
if(format.isNewLineAfterDeclaration())
println();
}
}
}
那么在写XML的时候,使用StandaloneWriter对象,就能将standalone="yes" 写入到XML declare中
OutputFormat format = OutputFormat.createPrettyPrint();
StandaloneWriter writer = new StandaloneWriter(new FileOutputStream(filePath),format);
writer.write(document);