无效的字符错误 - java中的XML格式

时间:2015-04-03 21:43:53

标签: java xml character

我有一个.txt文件:

Seven Pounds
Drama
13 martie 2009
8
tt0814314
/
Source Code
Mystery SF Thriller
1 aprilie 2011
8
tt0945513
/
V for Vendetta
Action Drama Thriller
16 martie 2006
8
tt0434409
/
Braveheart
Action Biography Drama
24 mai 1995
9
tt0112573
/
Se7en
Drama Mystery Thriller
22 septembrie 1995
9
tt0114369
/

我正在尝试做的是:在List<List<String>> L中从文件中读取所有内容,然后将它们写入XML格式。问题是我得到了INVALID_CHARACTER_ERR消息,即使我已经替换了空格字符。错误消息是这样的:

org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML              character is specified. 
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.createElement(CoreDocumentImpl.java:622)
at pa.tema5ex1.Tree.CreeazaRaportXML(Tree.java:246)
at pa.tema5ex1.PATema5Ex1.main(PATema5Ex1.java:22)

我现在所做的代码如下:

public void CreeazaRaportXML()
{
    try
    {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.newDocument();


        Element rootElement = doc.createElement("ColectieDeFilme");
        doc.appendChild(rootElement);

        for (int i = 0; i < colectieFilme.size(); i++)
        {
            for (int j = 0; j < colectieFilme.size(); j++)
            {
                String current = colectieFilme.get(i).get(j).replaceAll(" ", "").replace("\n", "");
                System.out.println("current -> " + current);
                Element dateFilmCurent = doc.createElement(current);
                rootElement.appendChild(dateFilmCurent);     
            }

        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\Users\\miTzuliK\\Documents\\NetBeansProjects\\[PA]Tema5Ex1\\RaportXML.xml"));
        transformer.transform(source, result);
        // Output to console for testing
        StreamResult consoleResult = new StreamResult(System.out);
        transformer.transform(source, consoleResult);
    }

    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:0)

1)我认为这是一个有点错误的方法,因为您使用数据作为标记名称。创建像

这样的xml结构会更正确
<film>
  <name>Seven Pounds</name>
  ...
  <id>tt0434409</id>
</film>

在这种情况下,您可以控制结构并避免XML标记名称中的意外不允许字符

2)如果你仍然想使用当前的方法尝试修剪字符串st结束,也许有特定的行分隔符。

3)它可能没有正确使用第二个for循环。您在初始List上按大小迭代,如果错误。想想应该是

for (int i = 0; i < colectieFilme.size(); i++) {
  List<String> filmStrings = colectieFilme.get(i);
  for (int j = 0; j < filmStrings.size(); j++) {
    ...
  }
}