public static void main(String[] args) {
try {
modifyElement("order","2","page-count","11111111");//调用函数
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//函数得功能是找到二级节点得一个属性为orderName值为orderValue得节点、并且修改他下面得一个名字为nodeName得节点得Text值修改为textValue
public static void modifyElement(String orderName,String orderValue,String nodeName,String textValue)throws IOException, XmlPullParserException
{
KXmlParser parser = new KXmlParser ();
parser.setInput (new FileReader ("xml/pdf.xml"));
parser.setFeature (XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
Document doc = new Document ();
doc.parse (parser);
//初始化doc
System.out.println(doc.getChildCount());
Element rootElement = doc.getRootElement();
//得到根节点
for(int j =1; j<rootElement.getChildCount();j=j+2)
{
String order = rootElement.getElement(j).getAttributeValue(null,orderName);
//只分析start节点不管结束节点所以每次加2
if(order.equals(orderValue))
{
Element functionEl = rootElement.getElement(j);//遍历根节点得
Element el = functionEl.getElement(null,nodeName);//根据节点得名字取得节点
el.clear();把这个节点得属性和值全部清空
el.addChild(el.TEXT,textValue);//添加个text值
}
}
File file = new File("xml/pdf.xml");
FileOutputStream out = new FileOutputStream(file);
KXmlSerializer serializer = new KXmlSerializer ();
serializer.setOutput (out, null);
doc.write (serializer);
serializer.flush ();
out.close();
//这里是重新写入这个文档
}