2011-07-26 56 views

Trả lời

21

Sử dụng XmlWriterSettings.OmitXmlDeclaration.

Đừng quên đặt XmlWriterSettings.ConformanceLevel thành ConformanceLevel.Fragment.

+0

Từ các tài liệu bạn liên kết đến: 'Các khai báo XML luôn bằng văn bản nếu ConformanceLevel được thiết lập để tài liệu, thậm chí nếu OmitXmlDeclaration được thiết lập để TRUE' – Cameron

+0

@Cameron, True và? –

+0

Nó sẽ không được đặt thành Tài liệu hầu hết thời gian? – Cameron

4

Bạn có thể phân lớp XmlTextWriter và ghi đè lên các phương pháp WriteStartDocument() để làm gì:

public class XmlFragmentWriter : XmlTextWriter 
{ 
    // Add whichever constructor(s) you need, e.g.: 
    public XmlFragmentWriter(Stream stream, Encoding encoding) : base(stream, encoding) 
    { 
    } 

    public override void WriteStartDocument() 
    { 
     // Do nothing (omit the declaration) 
    } 
} 

Cách sử dụng:

var stream = new MemoryStream(); 
var writer = new XmlFragmentWriter(stream, Encoding.UTF8); 
// Use the writer ... 

tham khảo: Đây blog post từ Scott Hanselman.

+0

cảm ơn, bất kỳ cách nào tốt hơn? Tôi không muốn phân lớp chỉ vì mục đích loại bỏ tuyên bố. – ninithepug

+0

@ninithepug: Không xa như tôi biết, xin lỗi. Bạn có thể bọc nó lên trong một phương pháp tĩnh ở đâu đó nếu bạn sử dụng nó thường xuyên, mặc dù. Điều đó sẽ giúp giữ cho nó sạch sẽ – Cameron

+0

cảm ơn người đàn ông, đánh giá cao nó – ninithepug

2

bạn có thể sử dụng XmlWriter.Create() với:

new XmlWriterSettings { OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment } 

    public static string FormatXml(string xml) 
    { 
     if (string.IsNullOrEmpty(xml)) 
      return string.Empty; 

     try 
     { 
      XmlDocument document = new XmlDocument(); 
      document.LoadXml(xml); 
      using (MemoryStream memoryStream = new MemoryStream()) 
      using (XmlWriter writer = XmlWriter.Create(memoryStream, new XmlWriterSettings { Encoding = Encoding.Unicode, OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment, Indent = true, NewLineOnAttributes = false })) 
      { 
       document.WriteContentTo(writer); 
       writer.Flush(); 
       memoryStream.Flush(); 
       memoryStream.Position = 0; 
       using (StreamReader streamReader = new StreamReader(memoryStream)) 
       { 
        return streamReader.ReadToEnd(); 
       } 
      } 
     } 
     catch (XmlException ex) 
     { 
      return "Unformatted Xml version." + Environment.NewLine + ex.Message; 
     } 
     catch (Exception ex) 
     { 
      return "Unformatted Xml version." + Environment.NewLine + ex.Message; 
     } 
    } 
Các vấn đề liên quan