c# - 创建 Xml 属性 json :Array using XElement and XNamespace C# classes

标签 c# xelement xnamespace

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

最佳答案

是的,您可以使用 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>

关于c# - 创建 Xml 属性 json :Array using XElement and XNamespace C# classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56328300/

相关文章:

c# - 使用 XElement 保存 XML 文件时,文件中的对齐方式也会发生变化,如何避免?

c# - 使用 C# 读取具有嵌套命名空间的 XML

c# - 使用 Page.ClientScript.RegisterClientScriptBlock 不起作用

c# - XML LINQ 查询不返回任何内容

c# - Serilog 文件接收器 - System.MissingMethodException : Method not found: Serilog. LoggerConfiguration

C#检查xml文件中的元素

c# - 使用 System.Xml.Linq API 设置 XML 命名空间

c# - 初始化类中的子类对象 - StackOverflowException

c# - 正确通知系统范围内命名的手动重置事件的所有监听器,然后立即重置它