【问题标题】:Can a field have XmlAttribute and XmlElement attributes?字段可以具有 XmlAttribute 和 XmlElement 属性吗?
【发布时间】:2018-07-30 16:23:27
【问题描述】:

我需要通过以下任一方式读取/写入 xml 元素。

<element param="..." set="...">
</element>

<element>
 <param>...</param>
 <set>...</set>
</element>

<element param="...">
 <set>...</set>
</element>

<element set="...">
 <param>...</param>
</element>

是否有可能有一个具有这种形式的班级来完成这项工作?

[XmlType("element")]
public class Element
{
  [XmlAttribute, XmlElement]
  public string param { get; set; }
  [XmlAttribute, XmlElement]
  public string set { get; set; }
}

【问题讨论】:

标签: c# xml xmlserializer


【解决方案1】:

您是否正在寻找一个 XML 类,它可以像这样具有同名的 Element 和 Attribute?

    [XmlRootAttribute(ElementName = "element")]
    public class ElementRoot
    {
        [XmlAttribute("param")]
        public string paramAtribute;

        [XmlElement("param")]
        public string paramElement;

        [XmlAttribute("set")]
        public string setAtribute;

        [XmlElement("set")]
        public string setElement;
    }

XML:

<?xml version="1.0" encoding="UTF-8"?>
<element xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" param="..." set="...">
   <param>...</param>
   <set>...</set>
</element>

【讨论】:

  • 是的,这很完美。好吧,我希望有一种更短的方法。
猜你喜欢
  • 2014-02-26
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多