2012-12-04 17 views
-1

我從.xlsx文件取得了一些字符串(字符串是簡單字符)。然後我試圖把這些字符串放在一個.xml文件中。但不幸的是,當我將這些字符串放在'createElement(StringVariableHere)'方法中時,出現以下錯誤:「org.w3c.dom.DOMException:INVALID_CHARACTER_ERR:指定了無效或非法的XML字符。」將字符串從Excel文件轉換爲.xml文件時出錯

我得到的字符串值以這樣的方式

switch (tempCell.getCellType()) { 
    case Cell.CELL_TYPE_STRING: 
    String tempColValue = tempCell.getStringCellValue(); 
} 

而這正是我嘗試添加自己的字符串值的行,它給我的錯誤。

Element titleChild = doc.createElement(StringVariableHere); 

我甚至嘗試使用下面的方法我在網上找到清理字符串:

public String stripNonValidXMLCharacters(String in) { 
    StringBuffer out = new StringBuffer(); // Used to hold the output. 
    char current; // Used to reference the current character. 

    if (in == null || ("".equals(in))) return ""; // vacancy test. 
    for (int i = 0; i < in.length(); i++) { 
     current = in.charAt(i); // NOTE: No IndexOutOfBoundsException caught here; it should not happen. 
     if ((current == 0x9) || 
      (current == 0xA) || 
      (current == 0xD) || 
      ((current >= 0x20) && (current <= 0xD7FF)) || 
      ((current >= 0xE000) && (current <= 0xFFFD)) || 
      ((current >= 0x10000) && (current <= 0x10FFFF))) 
      out.append(current); 
    } 
    return out.toString(); 
} 

而且我使用下面的檢查,如果它是有效還是無效,當我加入我的字符串它返回false:

XMLChar.isValidName(StringVariableHere) 

非常感謝你的時間。 Stefanos的。

+0

那麼什麼是你的問題? – djechlin

回答

1

你試過看看你在java中得到的字符串嗎?打印到控制檯或這樣的?

它讓我想起了解析辦公文檔的類似問題。解析器(apache POI)有時會給unicode無效的字符打破xml(一個例子是換行符)。

我不知道你在使用什麼語法分析器,但你可能必須在嘗試填充你的xml之前清理你的字符串。

添加後的細節後編輯。

你想寫什麼樣的xml?你能舉一個例子嗎? doc.createElement(StringVariableHere)表示您嘗試創建一個名爲StringVariableHere的元素。 I.E.

<StringVariableHere>there could be something here</StringVariableHere> 

<aRandomTag>StringVariableHere</aRandomTag> 
+0

謝謝。是的,我已經打印到控制檯,它工作正常。另外我使用相同的解析器(apache POI)。我上面發佈了一個我在網上找到的方法,以清理xml字符串... – Stefanos

+0

我編輯了我的答案。我認爲這是xml部分是錯誤的... – florent

+0

感謝您的幫助!我嘗試將字符串寫入xml作爲標記內容中的值,而不是作爲標記名稱。它正在工作。但最後有以下字符 你知道他們是什麼意思,以及如何刪除它們? – Stefanos