【问题标题】:Generate xml from c# class从 c# 类生成 xml
【发布时间】:2016-10-31 22:14:01
【问题描述】:

如果有人可以帮助我构建以下格式的 XML,我将不胜感激:

<requests>
<row no="1">
<fl val="Subject">Add Records Demo</fl>
<fl val="ContactName">John</fl>
<fl val="ProductName">Customer Care</fl>
<fl val="Email">john@demo.com</fl>
<fl val="Phone">002200330044</fl>
</row>
</requests>

这是我目前得到的:

<?xml version="1.0" encoding="utf-8"?>
<request>
<row>
<Subject>Add Records Demo</Subject>
<ContactName>John</ContactName>
<ProductName>Customer Care</ProductName>
<Email>john@demo.com</Email>
<Phone>002200330044</Phone>
</row>
</request>

这是我用来构建 xml 的代码

 List<ZohoVM> lzr = new List<ZohoVM>();
 lzr.Add(zvm);
 Request rp = new Request();
 rp.zohorow = lzr;
 XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
 ns.Add("", "");
 XmlSerializer xsdocument = new XmlSerializer(typeof(Request));
 StringWriter sw = new Utf8StringWriter();
 string xml = "";
 using (XmlWriter writer = XmlWriter.Create(sw))
 {
    xsdocument.Serialize(writer, rp, ns);
    xml = sw.ToString();
 }
 return xml;

我的请求类

[XmlRoot("request")]
public class Request
{
   public Request()
   {
      zohorow = new List<ZohoVM>();
   }
    [XmlElement("row")]
    public List<ZohoVM> zohorow { get; set; }
}

还有我的 ZohoVm 类

public class ZohoVM
{
   public string Subject { get; set; }
   public string ContactName { get; set; }
   public string ProductName { get; set; }
   public string Email { get; set; }
   public int Phone { get; set; }
}

我真正想要的是在 xml 标记中包含“fl 值”。提前致谢

【问题讨论】:

  • 既然你非常关心格式,为什么要使用序列化而不是 XmlDocument/Xdocument?

标签: c# .net xml xml-serialization


【解决方案1】:

我担心XmlSerializer 不像您希望的那样灵活。但是,您可以做的是从您想要实现的示例 XML 中提取一个 XML-Schema。使用上述方法,例如可以编写以下模式:

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="requests" type="Request"/>
  <xs:complexType name="RowFlag">
    <xs:simpleContent>
      <xs:extension base="xs:string">
        <xs:attribute type="xs:string" name="val" use="optional"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>
  <xs:complexType name="Row">
    <xs:sequence>
      <xs:element type="RowFlag" name="fl" maxOccurs="unbounded" minOccurs="0"/>
    </xs:sequence>
    <xs:attribute type="xs:byte" name="no"/>
  </xs:complexType>
  <xs:complexType name="Request">
    <xs:sequence>
      <xs:element type="Row" name="row"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

也许您可以根据需要细化此架构。然后,您可以使用带有/classes 选项的xsd.exe 生成创建此架构的类。在生成的代码中,您可以添加便利属性,然后必须使用XmlIgnore-attribute 进行标记。

【讨论】:

    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多