How do I load an org.w3c.dom.Document from XML in a string?

前端 未结 4 1355
暗喜
暗喜 2020-11-27 11:57

I have a complete XML document in a string and would like a Document object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)<

4条回答
  •  爱一瞬间的悲伤
    2020-11-27 12:36

    Whoa there!

    There's a potentially serious problem with this code, because it ignores the character encoding specified in the String (which is UTF-8 by default). When you call String.getBytes() the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!

    Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:

    import java.io.StringReader;
    import org.xml.sax.InputSource;
    …
            return builder.parse(new InputSource(new StringReader(xml)));
    

    It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.

提交回复
热议问题