Java关于XML文档排序的问题
2009-09-16 00:00:00 来源:WEB开发网要求根据用户需求,对指定的某一列的值(如第六列,则根据每一个id=”6”的value值进行排序),指定的排序顺序,进行排序,然后根据该顺序,交换每个行(即节点row的位置)的位置
2.此重点在于如何把子节点col与其父节点进行关联,并且,当排序列的值相同时,不能去除重复的值,必须都参与排序。开始考虑用一般的排序方法,但是不能把父节点关联起来,最后经他人提醒,用TreeMap来排序,把col的值作为TreeMap的key,父节点作为value。但 TreeMap会自动去掉重复值,因此,当col节点值相同时,他只去一个,为解决此问题,吧col值与父节点row的id联合作为key。解决此问题
3.主要java代码如下:
Java代码
public void sortByTreeMap() throws Exception
{
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = (XPath) factory.newXPath();
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("stat3.xml");
XPathExpression exprCol = xpath.compile("//row/col[@id='6']");
Object cols = exprCol.evaluate(doc, XPathConstants.NODESET);
NodeList colNodes = (NodeList) cols;
// 升序排序
Comparator comp = new Comparator()
{
//针对Float型的排序
/* public int compare(Object o1, Object o2)
{
Float f1 = (Float) o1;
Float f2 = (Float) o2;
if (f1 == null && f2 == null)
{
return 0;
}
else if (f1 == null)
{
return -1;
}
else if (f2 == null)
{
return 1;
}
else if (f1 == f2)
{
return 1;
}
else
{
return f1.compareTo(f2);
}
}*/
public int compare(Object o1, Object o2)
{
int i,j,k;
String strA,strB;
strA = (String)o1;
strB = (String)o2;
i = strA.lastIndexOf('-');
j = strB.lastIndexOf('-');
//此处解决,当col节点值相等时,根据其父节点的id值排序,以免相等值被TreeMap自动剔除
k = new Float(strA.substring(0, i)).compareTo(new Float(strB.substring(0, j)));
if(k == 0)
return new Float(strA.substring(i+2, strA.length())).compareTo(new Float(strB.substring(j+2, strB.length())));
else
return k;
}
};
// 降序排列
Comparator compDesc = new Comparator()
{
public int compare(Object o1, Object o2)
{
int i,j,k;
String strA,strB;
strA = (String)o1;
strB = (String)o2;
i = strA.lastIndexOf('-');
j = strB.lastIndexOf('-');
k = new Float(strB.substring(0, j)).compareTo(new Float(strA.substring(0, i)));
if(k == 0)
return new Float(strB.substring(j+2, strB.length())).compareTo(new Float(strA.substring(i+2, strA.length())));
else
return k;
}
};
// TreeMap treeMap = new TreeMap(comp);
TreeMap treeMap = new TreeMap(compDesc);
// Element resultElem = (Element) result.item(0) ;
for (int i = 0; i < colNodes.getLength(); i++)
{
Element colElem = (Element) colNodes.item(i);
Element parentElem = (Element) colElem.getParentNode();
//把col的值和对应的row 的id值组成一个字符串,以解决自动去除重复值的问题
treeMap.put(colElem.getAttribute("value") + "-" + parentElem.getAttribute("id"), parentElem);
}
Iterator iter = treeMap.entrySet().iterator();
XPathExpression exprResult = xpath.compile("//result");
Element resultNode = (Element) exprResult.evaluate(doc, XPathConstants.NODE);
int xuhao = 0;
String temp = "";
//排序后,交换行其父节点位置
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry) iter.next();
Element newNode = (Element)entry.getValue() ;
resultNode.appendChild(newNode);
}
saveXML("stat3-paixuDesc.xml", doc, "gb2312") ;
}
更多精彩
赞助商链接