似乎无法追查我获得HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
这是我的片段中的实际写作
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement;
Element childElement;
/* iterate through list */
Iterator<Map<String,String>> mapItrList = mapList.iterator();
Map<String, String> tempMap;
String[] tempKeySet;
while(mapItrList.hasNext())
{
tempMap = mapItrList.next();
/* process each data */
rootElement = doc.createElement(key);
rootElement.setAttribute("id", tempMap.get(key));
doc.appendChild(rootElement);
tempKeySet = tempMap.keySet().toString().replace("[", "").replace("]", "").split(",");
for(int temp = 0; temp < tempKeySet.length; temp++)
{
if(!tempKeySet[temp].equals(key))
{
childElement = doc.createElement("col");
childElement.setAttribute("id", tempKeySet[temp].toString());
childElement.appendChild(doc.createTextNode(tempMap.get(tempKeySet[temp])));
rootElement.appendChild(childElement);
}
else
{
/* do nothing */
}
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
//StreamResult result = new StreamResult(new File("file.xml"));
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
System.out.println("File saved!");
预期的XML结果
<Outer id="asdf">
<col id="asdf">
asdf
</col>
<col id="asdf3">
asdf
</col>
...
</Outer>
<Outer id="asdf">
<col id="asdf">
asdf
</col>
<col id="asdf3">
asdf
</col>
...
</Outer>
<Outer id="asdf">
<col id="asdf">
asdf
</col>
<col id="asdf3">
asdf
</col>
...
</Outer>
...
主要提示:
tempMap有这种结构
{
Status1=status1,
Status2=status2,
Type=myType,
Status3=status3,
Status4=status4
}
键指的是XML上的<Outer>
col指的是内循环
只是你知道为什么有一个while
,因为我迭代了一个Map列表所以它预计会有很多
在Map内部还有许多输入,因此在while循环的第一次迭代中,预期的xml将如下所示
<Outer id="asdf">
<col id="asdf">
asdf
</col>
<col id="asdf3">
asdf
</col>
...
</Outer>
但似乎有一个错误,即我无法追踪..
============================ UPDATE =============== =============
kdgregory
所指出的有同样问题的人的利益
你必须指定一个基本元素。这解决了我的情况