从XML Element及其子节点转换为Java中的String时,会出现奇怪的字符

时间:2012-05-03 23:44:24

标签: java xml

我使用下面链接中提到的转换器代码将xml元素及其子元素转换为xml字符串

How to convert xml Element and its child nodes into String in Java?

问题是我看到一些奇怪的字符,只有第一个元素文本内容是纯文本休息是一些奇怪的编码

如需快速参考,请输入代码

Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
StreamResult result = new StreamResult(new StringWriter()); 
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
String xmlString = result.getWriter().toString(); System.out.println(xmlString); 

输入如下所示

<Info ID="_65ae9406-63c9-4fd5-93a0-5ab1b5a3f3c7"
            IssueInstant="2012-02-11T09:53:52.722Z" Version="2.0"
            xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
            <Issuer>https://localhost:8080/</Issuer>
            <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <ds:SignedInfo>
                    <ds:CanonicalizationMethod
                        Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                    <ds:SignatureMethod
                        Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
                    <ds:Reference URI="#_65ae9406-63c9-4fd5-93a0-5ab1b5a3f3c7">
                        <ds:Transforms>
                            <ds:Transform
                                Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                        </ds:Transforms>
                        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                        <ds:DigestValue>IDHt1dgdR9k/toaocOxCVMiJhPjqRPyNSou4ywBA2YM=
                        </ds:DigestValue>
                    </ds:Reference>
                </ds:SignedInfo>
                <ds:SignatureValue>o5lTezATnGX+sllItfElMuabaFlpBed8wc8lAieigQ4JiIsgjIdHbg7gyyCpgk</ds:SignatureValue>

            <ds:Signature></Info>

2 个答案:

答案 0 :(得分:0)

尝试添加XML声明,该声明指定XML文件的编码(示例中为UTF-8)。也许它会有所帮助:)

<?xml encoding="UTF-8"?>

答案 1 :(得分:0)

请注意:DOMImplementationLS serialize to String in UTF-8 in Java

请注意这篇文章:

StringWriter output = new StringWriter();

String xml = output.toString();

上面的示例是在字符串编写器上调用toString,您在streamResult上调用它。

试着像那个例子一样打破它,看看它是否适合你。