2012-07-03 40 views
1

我試圖從一些數據在C#導出XML與C#

XDocument doc = XDocument.Parse(xml); 

後,我保存XML導出XML,我發現XML包含

<?xml version="1.0" encoding="utf-8"?> 

這是我沒有在進入所有,並導致像下面的問題。

<?xml version="1.0" encoding="utf-8"?> 
<?xml-stylesheet type="text/xsl" href="..\..\dco.xsl"?> 
<S> 
    <B> 
    </B> 
</S> 

我不想第一行出現,有什麼想法? 感謝您的回覆。

+0

你試過** LINQ to XML **嗎? –

回答

1

你所說的是 「之後」 你用字符串解析爲您見上你的結果是否包含重複的聲明?

現在我不知道你是如何保存你的回覆,但這裏是一個示例應用程序,它會產生類似的結果。

XDocument doc = XDocument.Parse("<?xml-stylesheet type=\"text/xsl\" href=\"dco.xsl\"?><S><B></B></S>"); 
      doc.Save(Console.OpenStandardOutput()); 

產生的結果爲:

<?xml version="1.0" encoding="utf-8"?> 
<?xml-stylesheet type="text/xsl" href="dco.xsl"?> 
<S> 
    <B></B> 
</S> 

這是你有問題。您需要在保存之前刪除xml聲明。這可以通過在保存xml輸出時使用xml編寫器來完成。下面是帶有擴展方法的示例應用程序,用於在沒有聲明的情況下編寫新文檔。

class Program 
    { 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Parse("<?xml-stylesheet type=\"text/xsl\" href=\"dco.xsl\"?><S><B></B></S>"); 
      doc.SaveWithoutDeclaration(Console.OpenStandardOutput()); 
      Console.ReadKey(); 
     } 


    } 

    internal static class Extensions 
    { 
     public static void SaveWithoutDeclaration(this XDocument doc, string FileName) 
     { 
      using(var fs = new StreamWriter(FileName)) 
      { 
       fs.Write(doc.ToString()); 
      } 
     } 

     public static void SaveWithoutDeclaration(this XDocument doc, Stream Stream) 
     { 
      byte[] bytes = System.Text.Encoding.UTF8.GetBytes(doc.ToString()); 
      Stream.Write(bytes, 0, bytes.Length); 
     } 
    } 
2

如果我理解正確,您需要一個沒有標題的XML文件。看看this answer

基本上,您需要初始化XmlWriterXmlWriterSettings類,然後調用doc.Save(writer)

+0

感謝您的回覆。 –