/**
 * 解析XML配置文件
 * @author shi
 */
public class ParseConfigFile {

private String configFile;
private Document doc;
private Map<String,ActionMapping> actionMappings; 

/**
 * 构造函数
 * @param configFile
 */
public ParseConfigFile(String configFile) {
this.configFile = configFile;
actionMappings = new HashMap<String,ActionMapping>();
init(this.configFile);
}

/**
 * 初始化,解析配置文件为Document对象
 * @param configFile
 */
private void init(String configFile) {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(configFile);
} catch (ParserConfigurationException e) {                                                                                  
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
 * 解析配置文件,内容保存Map的集合
 */
public Map<String,ActionMapping> parseXml() {
Element element=doc.getDocumentElement();//根元素,Element接口继承Node接口
if(element.hasChildNodes()) {
NodeList actionNodes = element.getElementsByTagName("action");//获取Action节点集合
for(int i=0; i<actionNodes.getLength(); i++) {
ActionMapping action = new ActionMapping();
Node actionNode = actionNodes.item(i);
//读取Action属性
if(actionNode.hasAttributes()) {
NamedNodeMap actionAttributes = actionNode.getAttributes();//元素的属性也是节点
for(int k=0; k<actionAttributes.getLength(); k++) {
Node n = actionAttributes.item(k);
String nodeName = n.getNodeName();
String nodeValue = n.getNodeValue();
if("path".equals(nodeName)) {
action.setPath(nodeValue);
} else if("type".equals(nodeName)) {
action.setType(nodeValue);
} else if("name".equals(nodeName)) {
action.setName(nodeValue);
} else if("scope".equals(nodeName)){
action.setScope(nodeValue);

}
}
//读取Forward属性
if(actionNode.hasChildNodes()) {
NodeList forwrdNodes = actionNode.getChildNodes();
List<ActionForward> actionForwardList = new ArrayList<ActionForward>();
for(int j=0; j<forwrdNodes.getLength(); j++) {
ActionForward forward = new ActionForward();
//错误点: 
Node forwardNode = forwrdNodes.item(i);
if(forwardNode.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(forwardNode.getNodeName());
}
                                                //--------------debug发现forwardAttributes为null,下面肯定就报空指针错了
                                                       NamedNodeMap forwardAttributes = forwardNode.getAttributes();
                                                //--------------
for(int h=0; h<forwardAttributes.getLength(); h++) {
Node n = forwardAttributes.item(h);
String nodeName = n.getNodeName();
String nodeValue = n.getNodeValue();
if("name".equals(nodeName)) {
forward.setName(nodeValue);
} else if("path".equals(nodeName)) {
forward.setPath(nodeValue);
}
}
actionForwardList.add(forward);
}
action.setActionForwardList(actionForwardList);
}
actionMappings.put(action.getPath(), action);
}
}
return actionMappings;
}

}
读取的xml文件:<?xml version="1.0" encoding="UTF-8"?><!-- 第一个版本,控制请求的转向 -->
<control-config>
<action path="/login"
type="msg.action.LoginAction"
>
<forward name="success" path="/index.jsp"></forward>
</action>
</control-config>说明:文件的路径什么没有问题!第一次获取节点的属性是可以的,但再拿到它的子节点,要获取子节点的属性,报“空指针”错!
    
      if(forwardNode.getNodeType() == Node.ELEMENT_NODE) {
  System.out.println(forwardNode.getNodeName());
     }这句话没有得到执行 说明forwardNode已经不是一个Element元素。我的理解:DOM包含的东西
  (1)元素:   元素是XML的基本构件。元素的子节点可以是其它元素、文本节点或两者都有。元素节点还可以只含有属性这一唯一类型的节点。  (2)属性:   属性节点包含关于元素节点的信息,但它不是元素的子节点   (3)文本:   文本节点文本信息,或干脆是空白的文本。   (4)文档:   文档节点是整个文档中所有其它节点的父节点
NamedNodeMap forwardAttributes = forwardNode.getAttributes();获取不到任何属性的集合,肯定出空指针错,我的代码的错误在那呢?怎样修改呢?请高手给予指点 真诚谢谢

解决方案 »

  1.   

    csdn 怎么才能上传调试的图片呢 ? 我想上传我debug的截图 
    forwardNode  debug发现: value =  DefferedTextImpl(id=107) 这样的话, forwardNode应该是一个Text节点了 可我实在发现不了我的错误在那?高手请给指点 谢谢
      

  2.   

    应该判断forwardNode是否为 elements 
      

  3.   

    请使用dom4j 那个好用多了...
      

  4.   

    我上次上传图片,也没有成功!我是用的dom4j
    dom4j的官方地址:http://www.dom4j.org/下载dom4j开发包:http://sourceforge.net/project/showfiles.php?group_id=16035下载完dom4j之后,在dom4j的docs/cookbook.html里有详细的入门手册,而在src/samples里面则是一些样例,详细介绍了怎样进行入门介绍dom4j的一个最大的实用之处是支持XPath表达式的查询,这样,我们可以在dom4j的Document结构中使用这种简单的表达式就可以快速找到我们需要的某个元素了.首先获得一个root元素,Element root=doc.getRootElement();而其他的元素也可以根据这个root元素来获得 本文示例包括:创建xml,修改xml(Xpath查询),递归打印xml
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.Element;
    import org.dom4j.io.XMLWriter;
    import java.io.*;
    import org.dom4j.Attribute;
    import org.dom4j.DocumentException;
    import org.dom4j.io.SAXReader;
    import java.util.List;
    import java.util.Iterator;
    import org.dom4j.QName;
    public class dom4j {
        public static void main(String[] argv) {
    dom4j ptree = new dom4j();
    ptree.modifyXML();
        }
              //使用XPath表达式的查询
         public void modifXML(File inputXml) {
           try { //创建一个读取xml文件的对象
             SAXReader saxReader = new SAXReader();
             //读取并获得xml文档
             Document document = saxReader.read(inputXml);
             //使用XPATH表达式从article元素中获得level节点列表
             List list = document.selectNodes("//article/@level");
             //创建一个迭代器.
             Iterator iter = list.iterator();
             while (iter.hasNext()) {
               //获得level节点的属性
               Attribute attribute = (Attribute) iter.next();
               if (attribute.getValue().equals("high"))
                 //设置属性的值
                 attribute.setValue("low");
             }
             list = document.selectNodes("//article/@date");
             iter = list.iterator();
             while (iter.hasNext()) {
               Attribute attribute = (Attribute) iter.next();
               if (attribute.getValue().equals("December-2007"))
                 attribute.setValue("October-2006");
             }
             list = document.selectNodes("//article");
             iter = list.iterator();
             while (iter.hasNext()) {
               Element element = (Element) iter.next();
               Iterator iterator = element.elementIterator("title");
               while (iterator.hasNext()) {
                 Element titleElement = (Element) iterator.next();//获得属性的文本.
                 if (titleElement.getText().equals("Java configuration with XML"))//重新设置属性的文本
                   titleElement.setText("good good study,day day up");
               }
             }
             list = document.selectNodes("//article/author");
             iter = list.iterator();
             while (iter.hasNext()) {
               Element element = (Element) iter.next();
               Iterator iterator = element.elementIterator("firstname");
               while (iterator.hasNext()) {
                 Element firstNameElement = (Element) iterator.next();
                 if (firstNameElement.getText().equals("angel"))
                   firstNameElement.setText("god");
               }
             }
             list = document.selectNodes("//article/author");
             iter = list.iterator();
             while (iter.hasNext()) {
               Element element = (Element) iter.next();
               Iterator iterator = element.elementIterator("lastname");
               while (iterator.hasNext()) {
                 Element lastNameElement = (Element) iterator.next();
                 if (lastNameElement.getText().equals("free"))
                   lastNameElement.setText("dark");
               }
             }
             OutputFormat format = OutputFormat.createPrettyPrint();
             format.setEncoding("GBK");
             XMLWriter output = new XMLWriter(
                 new FileWriter(new File("e:/example/books.xml")), format);
             output.write(document);
             output.close();
           }
           catch (DocumentException e) {
             System.out.println("aaaa" + e.getMessage());
           }
           catch (IOException e) {
             System.out.println("rrr" + e.getMessage());
           }
         }
         //访问其中某一特定节点
         public void modifyXML() {
           try {
             SAXReader sreader = new SAXReader();
             Document document = sreader.read(new File("e:/example/books.xml"));
             Element root = document.getRootElement();//获得根元素的名字
             String rootname = root.getName();
             System.out.println("rootname=" + rootname);
             //获得指定QName,prefix,uri
             QName qname = root.getQName();
             System.out.println(qname); //org.dom4j.QName@2d578e46 [name: catalog namespace: "org.dom4j.Namespace@bb7dc6cc [Namespace: prefix heavyz mapped to URI "http://www.qtone.cn"]"]
             System.out.println(qname.getNamespacePrefix()); //heavyz
             System.out.println(qname.getNamespaceURI()); //http://www.qtone.cn
             //获得当前元素指定属性的值
             String value = root.attributeValue("teacher");
             System.out.println(value); // yes
             List list = root.elements();
             Iterator iterator = list.iterator();
             while (iterator.hasNext()) {
               Element node = (Element) iterator.next();
               if ("Introductory".equals(node.attributeValue("level"))) {
                 System.out.println("let's go");
                 //重新设置当前元素的名字
                 node.setName("陈倩");
                 //重新设置属性level的值
                 node.setAttributeValue("level", "高级");
                 if ("October-2002".equals(node.attributeValue("date"))) {
                   node.setAttributeValue("date", "December-2001");
                 }
               }
               System.out.println(node.getName());
               if ("title".equals(node.getName())) {
                 node.setName("标题");
                 node.setText("中国万岁!");
               }
               else {
                 iterator = node.elementIterator();
               }
             }
             OutputFormat format = OutputFormat.createPrettyPrint();
             format.setEncoding("GBK");
             XMLWriter output = new XMLWriter(
                 new FileWriter(new File("e:/catalog/catalog_qname.xml")), format);
             output.write(document);
             output.close();
           }
           catch (DocumentException e) {
             System.out.println("aaaa" + e.getMessage());
           }
           catch (IOException e) {
             System.out.println("bbbb" + e.getMessage());
           }
         }
    }book.xml:
    <?xml version="1.0" encoding="GBK"?>
    <books>
      <!--—An XML Example--><?target text?>
      <bookone title="XML study" publisher="angellove workers">
        <article level="high" date="December-2007">
          <title>Java configuration with XML</title>
          <author>
            <firstname>angel</firstname>
            <lastname>free</lastname>
          </author>
        </article>
      </bookone>
    </books>修改后的bookxml:<?xml version="1.0" encoding="GBK"?>
    <books> 
      <!--—An XML Example--><?target text?>
      <bookone title="XML study" publisher="angellove workers"> 
        <article level="high" date="December-2007"> 
          <标题>中国万岁!</标题>  
          <author> 
            <firstname>angel</firstname>  
            <lastname>free</lastname> 
          </author> 
        </article> 
      </bookone> 
    </books>
      

  5.   

     你说forwrdNodes为 NULL 那么 forwrdNodes.item(i)这个就没有取到值、。
    你把  NodeList forwrdNodes = actionNode.getChildNodes 在这句下面输出forwrdNodes  看看
      

  6.   

     NamedNodeMap forwardAttributes = forwardNode.getAttributes(); 
     错误的点,forwardAttributes 为 null 。
     这样还是没解决掉,换了个方法,用jdom了,哎 还是得用人家的啊  
    /**
     * 通过Jdom解析xml配置文件
     * @author shi
     */
    public class ParseConfigFileJdom { private String configFile;
    private Map<String,ActionMapping> actionMappings; 
    private Document doc;
    /**
     * 构造函数
     * @param configFile
     */
    public ParseConfigFileJdom(String configFile) {
    this.configFile = configFile;
    actionMappings = new HashMap<String,ActionMapping>();
    init(this.configFile);
    }

    /**
     * 初始化,解析配置文件为Document对象
     * @param configFile
     */
    private void init(String configFile) {
    SAXBuilder sb = new SAXBuilder();
    try {
    doc = sb.build(configFile);
    } catch (JDOMException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }

    }

    /**
     * 解析配置文件,内容保存Map的集合
     */
    public Map<String,ActionMapping> parseXml() {
    Element rootEle = doc.getRootElement();
    try {
    //取得所有的ActionElelment
    List<Element> eleActionList  = (List<Element>)XPath.selectNodes(rootEle, "/control-config/action");
    for(int i=0; i<eleActionList.size(); i++) {
    Element eleAction = eleActionList.get(i);
    ActionMapping actionMapping = new ActionMapping();
    //Action属性
    String path = eleAction.getAttributeValue("path");
    String type = eleAction.getAttributeValue("type");
    actionMapping.setPath(path);
    actionMapping.setType(type);

    //取出某个Action的所有的Forward
    List eleForwardList = eleAction.getChildren("forward");
    List<ActionForward> actionForwardList = new ArrayList<ActionForward>();//所有的Forward存入集合
    for(int j=0; j<eleForwardList.size(); j++) {
    Element eleForward = (Element)eleForwardList.get(j);
    ActionForward actionForward = new ActionForward();

    //Forward属性
    String fname = eleForward.getAttributeValue("name");
    String fpath = eleForward.getAttributeValue("path");
    actionForward.setName(fname);
    actionForward.setPath(fpath);

    actionForwardList.add(actionForward);
    }
    actionMapping.setActionForwardList(actionForwardList);
    actionMappings.put(eleAction.getAttributeValue("path"), actionMapping);//某个Action配置存入Map
    }
    } catch (JDOMException e) {
    e.printStackTrace();

    return actionMappings;
    }
    }谢谢大家了。
      

  7.   

    List list =new ArrayList();   
    Reader readera = Resources.getResourceAsReader("properties/Attribute.xml");//这个类 用的是Ibatis中的 其 他的包中实现不了这样的
       SAXReader reader = new SAXReader();
       Document doc = reader.read(readera);
        Element root=doc.getRootElement();
       Iterator i = root.elementIterator("attribute");
       Element  foo=null;
       while(i.hasNext()){
       foo  = (Element) i.next();
       Attribute att=new Attribute();
       att.setId(Integer.parseInt(foo.attributeValue("id")));
       att.setPdtype(Integer.parseInt(foo.attributeValue("pdtype")));
       att.setAttributeValue(Integer.parseInt(foo.attributeValue("attributeValue")));
       list.add(att);
       }
       return list;
      

  8.   

    Iterator i = root.elementIterator("attribute");//attribute这个是某个节点 为了的这个节点中的属性值