문제

나는 건물을 짓고있다 xmldocument XML 문서가있는 .NET에서 즉시. 그런 다음 그것으로 그것을 변환합니다 변환() 방법의 방법 xslcompiledtransform.

변환 () 메소드는 인코딩에 대한 잘못된 문자가 스트림에서 발견 되었기 때문에 예외를 던졌습니다. Visual Studio에서 Textvisualizer의 도움으로 문자열을 복사/붙여 넣을 때 Altova xmlspy, 인코딩 문제를 찾지 못합니다.

문서에 UTF-16 헤더를 추가하여 UTF-16으로 렌더링하고 결과 텍스트에서 변환을 호출하여 BOM에 대해 불평했습니다. 아래는 내가 사용한 코드의 단순화 된 버전입니다.

            XmlDocument document = new XmlDocument();
            XmlDeclaration decl = document.CreateXmlDeclaration("1.0", "UTF-16", null);
            document.AppendChild(decl);

            XmlNode root = document.CreateNode(XmlNodeType.Element, "RootNode", "");
            XmlNode nodeOne = document.CreateNode(XmlNodeType.Element, "FirstChild", null);
            XmlNode nodeTwp = doc.CreateNode(XmlNodeType.Element, "Second Child", null);

            root.AppendChild(nodeOne);
            root.AppendChild(nodeTwo);
            document.AppendChild(root);

결과적으로 다음과 같은 문자열에 글을 쓰고 있습니다.

        StringBuilder sbXml = new StringBuilder();
        using (XmlWriter wtr = XmlWriter.Create(sbXml))
        {
            xml.WriteTo(wtr);
            // More code that calls sbXml.ToString());
        }

BOM을 추가하거나 xslcompiledtransform.transform.transform을 얻으려면 어떻게해야합니까?

도움이 되었습니까?

해결책

XML 선언을 수동으로 추가 할 필요가 없습니다.

이 코드는 BOM과 선언을 출력에 추가합니다.

XmlDocument document = new XmlDocument(); 
// XmlDeclaration decl = document.CreateXmlDeclaration("1.0", "UTF-16", null); 
// document.AppendChild(decl); 
XmlNode root = document.CreateNode(XmlNodeType.Element, "RootNode", ""); 
XmlNode nodeOne = document.CreateNode(XmlNodeType.Element, "FirstChild", null);
XmlNode nodeTwo = document.CreateNode(XmlNodeType.Element, "SecondChild", null); 
root.AppendChild(nodeOne); 
root.AppendChild(nodeTwo); 
document.AppendChild(root);

using(MemoryStream ms = new MemoryStream())
{
    StreamWriter sw = new StreamWriter(ms, Encoding.Unicode);
    document.Save(sw);
    Console.Write(System.Text.Encoding.Unicode.GetString(ms.ToArray()));
}

바이트 []로 출력이 필요한 경우 Ms.ToArray ()의 출력을 사용할 수 있습니다. 그렇지 않으면 적절한 system.text.encoding 인코딩을 사용하여 바이트 []를 다양한 인코딩으로 변환 할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top