给元素添加属性报异常《INVALID_CHARACTER_ERR: 指定的 XML 字符无效或非法》

来源:互联网 发布:python服务端 编辑:程序博客网 时间:2024/06/06 07:29

今天练习了一个使用DOM创建xml文档,想通过自己的方式给name元素添加一个age属性,可惜的是报了异常,提示:INVALID_CHARACTER_ERR: 指定的 XML 字符无效或非法。异常代码如下:

Document doc=null;
  doc=builder.newDocument();
  Element info=doc.createElement("info");
  Element name=doc.createElement("name");
  Element address=doc.createElement("address");
  String age="";
  name.setAttribute(age,"12");

按照提示name.setAttribute(xx,xx)中的参数都是String类型的,我上面写的应该不会出错,为什么会报异常?

仔细看看代码就明白了,虽然定义了age,但是它没有值,而在setAttribute()中设置的时候,其实用到的是age的值,而不是age。   地址和地址的值是两码事,明白了这一点后应该把代码改写为:

Document doc=null;
  doc=builder.newDocument();
  Element info=doc.createElement("info");
  Element name=doc.createElement("name");
  Element address=doc.createElement("address");

  name.setAttribute("age","12"); 

任何事情自己要去学习,搞明白,不能一味的听别人的!

0 0