Asp.net
Xdocument 不列印聲明
我嘗試使用 domainpeople.com API,我需要使用 XML。
目前我有一個錯誤說“apiProtocol is not found”我猜我的 Xml 文件格式不正確。
目前發送的 xml 是:
<apiProtocol version="1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNameSpaceSchemaLocation="checkrequest.xsd"> <checkRequest user="ifuzion" password="fish4gold121" reference="123456789"> <domain name="google.com" /> </checkRequest> </apiProtocol>顯然該
<?xml?>部分沒有列印出來。我的程式碼基本上類似於:
XDocument xDocument = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement("Books"));(為了簡單起見,我刪除了我的程式碼,但結構完全相同)。
XDocument 是否有任何理由不列印出該
<?xml?>部分?似乎使用 XmlDocument 它可以工作,但不能使用 XDocument ……有什麼提示嗎?
你是如何列印出你的內容的
XDocument?該
.ToString()方法不包含 xml 標頭,但該.Save()方法包含。編輯:這裡給出了相同的答案。
你如何保存它?如果我執行以下操作,xml 聲明就會出現:
XDocument xDocument = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement("Books")); xDocument.Save(@"c:\temp\file.xml");輸出如下所示:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Books />但是,如果我改為傳遞 XmlWriter 實例,則該 XmlWriter 的設置似乎會覆蓋 XDocument 中所述的內容:
XDocument xDocument = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement("Books")); StringBuilder sb = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(sb)) { xDocument.Save(writer); } Console.WriteLine(sb.ToString());輸出如下所示:
<?xml version="1.0" encoding="utf-16" standalone="yes"?><Books />請注意編碼如何更改為“utf-16”並且縮進已更改。如果添加指示編碼(以及您想要控制的任何其他設置)的 XmlWriterSettings 實例,您將獲得更好的結果。以下程式碼符合您的預期:
XDocument xDocument = new XDocument( new XDeclaration("1.0", "UTF-8", "yes"), new XElement("Books")); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.ConformanceLevel = ConformanceLevel.Document; settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(@"c:\temp\xdocument.xml", settings)) { xDocument.Save(writer); }輸出:
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <Books />