将Java转换为XML时发生命名空间错误

时间:2018-06-19 10:59:09

标签: java xml-parsing domexception

我尝试使用Java创建类似下面的XML字符串。

<entry gd:etag="*" xmlns="http://www.w3.org/2005/Atom">
  <id>http://www.google.com/m8/feeds/contacts/default/base/contactid</id>
  <category scheme="http://schemas.google.com/g/2005#kind"
    term="http://schemas.google.com/contact/2008#contact"/>
  <gd:name>
    <gd:fullName>{Name}</gd:fullName>
  </gd:name>
  <gd:email rel="http://schemas.google.com/g/2005#work"
    primary="true"
    address="{Email}" displayName="Mani"/>
  <content type="text">Notes</content>
  <gd:phoneNumber rel="http://schemas.google.com/g/2005#other"
    primary="true">{MobileNumber}</gd:phoneNumber>
</entry>

我的java代码是

DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();  
DocumentBuilder docBuilder = docBuildFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element entry = doc.createElement("entry");
entry.setPrefix("gd");  
entry.setAttribute("gd:etag","*");
doc.appendChild(entry);
Element id = doc.createElement("id");
id.setTextContent("http://www.google.com/m8/feeds/contacts/default/base/"+contactID);
entry.appendChild(id);
Element category = doc.createElement("catagory");
category.setAttribute("scheme","http://schemas.google.com/g/2005#kind");
category.setAttribute("term","http://schemas.google.com/contact/2008#contact");
entry.appendChild(category);
Element name = doc.createElement("gd:name");
Element fullName = doc.createElement("gd:fullname");
fullName.setTextContent(newName);
name.appendChild(fullName);
entry.appendChild(name);
....
StringWriter stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
DOMSource source = new DOMSource(entry);
TransformerFactory transformFactory = TransformerFactory.newInstance();
Transformer transformer = transformFactory.newTransformer();
transformer.transform(source , result);
String xmlString = stringWriter.toString();

当我运行上面的代码时,我得到以下异常

  

线程中的异常&#34; main&#34; org.w3c.dom.DOMException:NAMESPACE_ERR:An   尝试以某种方式创建或更改对象   名称空间不正确。
  at java.xml / com.sun.org.apache.xerces.internal.dom.NodeImpl.setPrefix()

有人可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:0)

最后找到我错了。 我只是在代码中更改了以下行

Element entry = doc.createElement("entry");

Element entry = doc.createElementNS("http://www.w3.org/2005/Atom","entry");

现在我得到了所需的XML字符串。