日期:2014-05-20  浏览次数:20914 次

操作xml文件问题
能不能像操作数据库那样读写xml文件?

------解决方案--------------------
看看api里javax.xml这部分
要用到DocumentBuilderFactory,DocumentBuilder这些
------解决方案--------------------
JDK 1.5 中还增加了 XPath,用于查询数据很方便的。
------解决方案--------------------
jdomAPI
------解决方案--------------------
可以用apche的类库,我前两天正好在公司写了个操作xml文件的类,给你看下:
..............

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;

...........

DomainModel domainModel = (DomainModel) request.getSession().getAttribute("TABLE");
InputSource is = new InputSource("d:\\huaxia\\huaxiaweb\\src\\main\\resources\\myapp.struts.xml");
is.setEncoding("UTF-8");
SAXBuilder sb = new SAXBuilder();
Document structsXML;
try {
structsXML = sb.build(is);
} catch (JDOMException e1) {
// TODO Auto-generated catch block
logger.info(e1.getMessage());
return;
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.info(e1.getMessage());
return;
}

// StructsXML文件的根元素
Element root = structsXML.getRootElement();

Element actionMapping = root.getChild("action-mappings");

boolean haveMainAction = false;
boolean haveUpdateAction = false;
boolean haveCreateAction = false;
java.util.List<Element> elements = actionMapping.getChildren();
for(Element el: elements){
if( el.getAttributeValue("path").equals( ("/" + domainModel.getTableNameInJava() + "MainAction"))
&& el.getAttributeValue("parameter").equals("method")
&& el.getAttributeValue("name").equals((domainModel.getTableNameInJavaFirstLow() + "Form"))){
logger.info(domainModel.getTableNameInJava() +"MainAction has already existed.");
haveMainAction = true;
}
if( el.getAttributeValue("path").equals( ("/" + domainModel.getTableNameInJava() + "CreateAction"))
&& el.getAttributeValue("input").equals( ("/" + domainModel.getTableNameInJava() + "Create.jsp"))){
logger.info(domainModel.getTableNameInJava() + "CreateAction has already existed.");
haveCreateAction = true;
}
if( el.getAttributeValue("path").equals( ("/" + domainModel.getTableNameInJava() + "UpdateAction"))
&& el.getAttributeValue("input").equals( ("/" + domainModel.getTableNameInJava() + "Update.jsp"))){
logger.info(domainModel.getTableNameInJava() + "UpdateAction has already existed.");
haveUpdateAction = true;
}
}


------解决方案--------------------
我解释下:
 InputSource is = new InputSource("d:\\huaxia\\huaxiaweb\\src\\main\\resources\\myapp.struts.xml"); 
把一个xml文件读入InputSource类 这个类是jdom的一个部分。
is.setEncoding("UTF-8"); 
SAXBuilder sb = new SAXBuilder(); 
Document structsXML;