【问题标题】:Web API XML Deserialization : Node with multiple child nodes with same tag nameWeb API XML反序列化:具有多个具有相同标签名称的子节点的节点
【发布时间】:2019-11-10 02:00:12
【问题描述】:

我正在使用 Visual Studio 2015 创建一个 Web API。 我的请求 xml 包含具有相同标签名称的子节点。

<TestData>
   <TestChild>
      <input>
       <name ="Test1"/>
       <value="DUMMY VALUE1"/>
      </input>
      <input>
       <name ="Test1"/>
       <value="DUMMY VALUE1"/>
      </input>
      <input>
       <name ="Test1"/>
       <value="DUMMY VALUE1"/>
      </input>
 </TestChild>
</TestData>

我已将 XRoot 和 XElement 属性添加到 .net c# 对象,如下所示:

    [XmlRoot]
    public class TestData
    {
        [XmlElement]
        public TestChild TestChild { get; set; }
    }

    public class TestChild
    {
        [XmlElement]
        public input[] input { get; set; }
    }

    public class input
    {
        [XmlElement]
        public string name { get; set; }
        [XmlElement]
        public string value { get; set; }
    }

但是通过上述代码生成的示例 xml 看起来有点不同。它添加一个父 input 标签,然后在其中添加多个输入标签。我需要 xml 看起来像上面共享的那样。

<TestData xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <TestChild>
    <input>
      <input>
        <name>sample string 1</name>
        <value>sample string 2</value>
      </input>
      <input>
        <name>sample string 1</name>
        <value>sample string 2</value>
      </input>
    </input>
  </TestChild>
</TestData>

我试过设置

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

但这也无济于事。 我是 Web API 的新手,如有任何帮助/建议,我们将不胜感激。

【问题讨论】:

  • 正在摆脱TestChild 类并将public input[] TestChild 添加到TestData 一个选项?

标签: c# asp.net .net asp.net-web-api


【解决方案1】:

保留 TestChild 属性,但删除 TestChild 类
试试这样:

    [XmlRoot]
    public class TestData
    {
        [XmlElement]
        public input[] TestChild { get; set; }
    }

    public class input
    {
        [XmlElement]
        public string name { get; set; }
        [XmlElement]
        public string value { get; set; }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多