2012-08-03 6 views
1

UTF-16으로 인코딩 된 문자열이 있습니다.XML 문자열에서 유효하지 않은 문자를 대체하는 방법은 무엇입니까?

다음
Character reference "&#x0" is an invalid XML character 

나는 XML을 구문 분석하는 데 사용되는 코드는 다음과 같습니다 : javax.xml.parsers.DocumentBuilder를 사용하여 구문 분석 할 때,이 같은 오류가 발생했습니다

InputSource inputSource = new InputSource(); 
inputSource.setCharacterStream(new StringReader(xmlString)); 
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder parser = factory.newDocumentBuilder(); 
org.w3c.dom.Document document = parser.parse(inputSource); 

내 질문은, (에 의해 잘못된 문자를 대체하는 방법 공간)?

+4

당신은이 * 전에 * 당신이 XML을 구문 분석해야합니다. –

+0

구문 분석을하기 전에이 작업을 수행해야한다는 것을 알고 있지만 질문은 수행하는 방법입니다. – user1574322

+1

확인 다른 유래 스레드에서이 대답은 : : http://stackoverflow.com/a/4237934/405117 – Vikram

답변

0

잘못된 xml entity을 구문 분석하려고하는데 예외적 인 경우입니다. 상황에 맞게 UTF-16에 대해 걱정할 필요가없는 것 같습니다.

몇 가지 설명과 예를 찾으십시오. here.

예를 들어 valid xml& 문자를 사용할 수 없으므로 대신 &을 사용해야합니다. 여기서 &은 xml 엔터티입니다.

위 예제는 xml 엔티티가 무엇인지 이해하기 위해 자체적으로 설명해야한다고 가정합니다.

내가 알고있는 것처럼 유효하지 않은 일부 XML 엔티티가 있습니다. 그러나 다시는 걱정할 필요가 없습니다. &을 새로 추가 xml entity을 선언 할 수 있습니다. 자세한 내용은 위의 문서를 살펴보십시오.


편집 : XML이 유효하게 & 문자가 가정.

1

String.replaceAll을 사용하고 유효하지 않은 문자 패턴을 전달하기 만하면됩니다.

+0

내 xmlString을은 같은 것입니다 이것은 내 콘텐츠    �  �  � 패턴은 무엇입니까? 감사합니다. – user1574322

0

StringEscapeUtils()

escapeXml

public static void escapeXml(java.io.Writer writer, 
          java.lang.String str) 
         throws java.io.IOException 

Escapes the characters in a String using XML entities. 

For example: "bread" & "butter" => "bread" & "butter". 

Supports only the five basic XML entities (gt, lt, quot, amp, apos). 
Does not support DTDs or external entities. 

Note that unicode characters greater than 0x7f are currently escaped to their 
numerical \\u equivalent. This may change in future releases. 

Parameters: 
    writer - the writer receiving the unescaped string, not null 
    str - the String to escape, may be null 
Throws: 
    java.lang.IllegalArgumentException - if the writer is null 
    java.io.IOException - if there is a problem writing 
See Also: 
    unescapeXml(java.lang.String) 
관련 문제