[英]Why can't I set the XDocument XDeclaration encoding type to iso-8859-1?
[英]Why does XDeclaration ignore the encoding parameter I set
我正在嘗試使用XDeclaration
生成XML文件,這將導致以下情況
<?xml version="1.0"?>
。
運行代碼時,我不斷得到的是
<?xml version="1.0" encoding="utf-8"?>
。
因此,問題是,無論我在XDeclaration
的encoding參數中進行了什么更改,它都會不斷向我的聲明中添加一個編碼標記。
我想要的甚至有可能嗎? 如果可以的話,有人可以向我解釋嗎?
首先,我嘗試將OmitXmlDeclaration
設置為true。 但這完全刪除了我的聲明,然后我根本無法使用XDecleration類。
其次,當我將XDecleration設置為此時:
new XDeclaration("1.0", string.Empty, "yes")
我明白了
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
當我將XDecleration設置為此時:
new XDeclaration("1.0", string.Empty, string.Empty)
我明白了
<?xml version="1.0" encoding="utf-8"?>
因此,我知道它確實響應了我輸入的內容,但是編碼部分卻沒有。 編輯:我也試圖將參數設置為null
而不是string.Empty
。 這也不起作用。
public FileResult Download()
{
var doc = new XDocument(
new XDeclaration("1.0", string.Empty, string.Empty),
new XElement("foo",
new XAttribute("hello", "world")
)
);
using (var stream = new MemoryStream())
{
var settings = new XmlWriterSettings()
{
OmitXmlDeclaration = false,
Indent = true,
};
using (var writer = XmlWriter.Create(stream, settings))
{
doc.Save(writer);
}
stream.Position = 0;
return File(stream.ToArray(), "text/xml", "HelloWorld.xml");
}
}
@HimBromBeere給了我解決方案。 他給出了答案,其中包含以下鏈接。
cookcomputing.com/blog/archives/000577.html 。 在這里,您可以覆蓋編碼參數。 這對我有用。
默認情況下,保存XML文檔時,XML保存方法將覆蓋我們通過XDeclaration提供的編碼方法。 最簡單的方法是創建一個內存流並修補編碼方法。 請參考以下代碼片段
public static void PatchEncoding(string xmlPath, XDocument xmlDoc, string encoding = "windows-1251")
{
using (var stream = new MemoryStream())
using (XmlTextWriter xmlwriter = new XmlTextWriter(stream, Encoding.GetEncoding(encoding)))
{
xmlDoc.Save(xmlPath);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.