【问题标题】:Creating Xml attribute json:Array using XElement and XNamespace C# classes使用 XElement 和 XNamespace C# 类创建 Xml 属性 json:Array
【发布时间】:2019-05-27 14:49:53
【问题描述】:

我正在尝试构建如下所示的 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”前缀但没有成功。

【问题讨论】:

    标签: c# xelement xnamespace


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2013-12-10
      • 2012-04-06
      • 1970-01-01
      • 2011-02-04
      • 2021-10-21
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      相关资源
      最近更新 更多