我正在尝试构建如下所示的Xml(从另一个问题中获取),但是使用XElement / XNamespace类:
<person xmlns:json='http://james.newtonking.com/projects/json' id='1'>
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array='true'>Admin</role>
</person>
因此,我可以使用Newtonsoft.Json.JsonConvert.SerializeXmlNode()进行序列化并维护正确的数组。
我遇到的问题是创建 json:Array ='true'。
其他示例显示XmlDocument类或Xml字符串的原始创建,但是有没有办法使用XElement实现呢?我已经尝试过使用XNamespace做几件事来尝试创建“ json”前缀,但没有成功。
答案 0 :(得分:1)
是的,您可以使用XElement来实现。例如:
XNamespace json = "http://james.newtonking.com/projects/json";
XDocument xml = new XDocument(new XElement("person",
new XAttribute(XNamespace.Xmlns + "json", json),
new XAttribute("id", 1),
new XElement("name", "Alan"),
new XElement("url", "http://www.google.com"),
new XElement("role", new XAttribute(json + "Array", true), "Admin")));
将产生以下内容:
<person xmlns:json="http://james.newtonking.com/projects/json" id="1">
<name>Alan</name>
<url>http://www.google.com</url>
<role json:Array="true">Admin</role>
</person>