我通过以下代码
序列化MyXMLData类var series = [
{ slug: "et", title: "Buller" },
{ slug: "fem", title: "Bøller" },
{ slug: "to", title: "Agnes" },
{ slug: "tre", title: "Cara" }
];
var sorted = _.sortBy(series, 'title');
document.getElementById('sorted').innerHTML = JSON.stringify(sorted);
输出标题类似于
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="sorted"></div>
我的问题
1)我想要包含类似`?xml version =“1.0”encoding =“utf-8”的编码数据?&gt; 。怎么做?
2)我想更改命名空间并放置我自己的自定义namesapace(这是我的要求)
而不是XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData));
FileStream fileStream = new FileStream(fileName, FileMode.Create);
xmlSerializer.Serialize(fileStream, myXMLData);
fileStream.Close();
,我只想要<?xml version="1.0"?>
<MyXMLData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
之类的东西。
我可以读取xml文件并在写入内容后替换它们,但我想知道,当写入xml文件时,是否有一步完成此操作?
答案 0 :(得分:2)
您可以执行以下步骤 1.达到你的第一个要求:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData));
var fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "filename.xml");
var appendMode = false;
var encoding = Encoding.GetEncoding("UTF-8");
using(StreamWriter sw = new StreamWriter(fname, appendMode, encoding))
{
xmlSerializer.Serialize(sw, MyXMLData);
}
对于XMLSerializer类的构造函数,添加如下命名空间:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData), "http://www.mydata.org");
答案 1 :(得分:0)
此解决方案正常运行
XmlSerializer xmlSerializer = new XmlSerializer(typeof(MyXMLData));
XmlSerializerNamespaces ns1 = new XmlSerializerNamespaces();
ns1.Add("", "http://www.mydata.org");
Encoding encoding = Encoding.GetEncoding("UTF-8");
using (StreamWriter sw = new StreamWriter(fileName, false, encoding))
{
xmlSerializer.Serialize(sw, myXMLData, ns1);
}