0

XML 문서로 .NET에서 XmlDocument을 즉석으로 작성합니다. 그런 다음 Transform() 메서드를 사용하여 XslCompiledTransform으로 변환합니다..NET에서 BOM이있는 문자열에 UTF-16 XMLDocument를 작성하는 방법

인코딩에 유효하지 않은 문자가 스트림에서 발견되었으므로 Transform() 메서드에서 예외가 발생했습니다. Visual Studio의 TextVisualizer를 사용하여 문자열을 복사/붙여 넣기를 Altova XmlSpy에 붙여 넣으면 인코딩 문제가 발견되지 않습니다.

문서에 UTF-16 헤더를 추가하여 UTF-16으로 렌더링하고 결과 텍스트에서 Transform을 호출하여 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은 BOM에 대해 걱정하지 얻기 위해 무엇을해야 하는가?

답변

3

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())); 
} 

출력을 byte []로해야하는 경우 ms.ToArray()의 출력을 사용할 수 있습니다. 그렇지 않으면 적절한 System.Text.Encoding 인코딩을 사용하여 바이트 []를 다양한 인코딩으로 변환 할 수 있습니다.

관련 문제