mlAttributeOverrides集合元素重写XML元素名

mlAttributeOverrides集合元素重写XML元素名

本文介绍了如何使用XmlAttributeOverrides集合元素重写XML元素名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经得到了正在被System.Xml.XmlSerialization东西序列化一个非常基本对象的对象模型。我需要使用XmlAttributeOverrides功能的子元素的集合设置的XML元素名称。

I've got a very basic object object model that is being serialized by the System.Xml.XmlSerialization stuff. I need to use the XmlAttributeOverrides functionality to set the xml element names for a collection of child elements.

public class Foo{
  public List Bars {get; set; }
}

public class Bar {
  public string Widget {get; set; }
}



采用标准的XML序列化,这会出来为

using the standard xml serializer, this would come out as

 <Foo>
  <Bars>
    <Bar>...</Bar>
  </Bars>
 </Foo>

我需要使用XmlOverrideAttributes使这一说。

I need to use the XmlOverrideAttributes to make this say

 <Foo>
  <Bars>
    <SomethingElse>...</SomethingElse>
  </Bars>
 </Foo>

但我似乎无法得到它重命名集合中的子元素...我可以重命名集合本身...我可以重命名根......不知道我做错了。

but I can't seem to get it to rename the child elements in the collection... i can rename the collection itself... i can rename the root... not sure what i'm doing wrong.

这里的代码,我现在所拥有的:

here's the code I have right now:

XmlAttributeOverrides xOver = new XmlAttributeOverrides();

var bars = new XmlElementAttribute("SomethingElse", typeof(Bar));
var elementNames = new XmlAttributes();
elementNames.XmlElements.Add(bars);
xOver.Add(typeof(List), "Bars", elementNames);

StringBuilder stringBuilder = new StringBuilder();
StringWriter writer = new StringWriter(stringBuilder);
XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver);
serializer.Serialize(writer, someFooInstance);

string xml = stringBuilder.ToString();



但是,这并不改变元素的名称在所有...我在做什么错?

but this doesn't change the name of the element at all... what am I doing wrong?

感谢

推荐答案

要做到这一点,你要 [XmlArray] [XmlArrayItem] (理想情况下,使其明确两者):

To do that you want [XmlArray] and [XmlArrayItem] (ideally both of to make it explicit):

using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
public class Foo {
    public List<Bar> Bars { get; set; }
}
public class Bar {
    public string Widget { get; set; }
}
static class Program {
    static void Main() {
        XmlAttributeOverrides xOver = new XmlAttributeOverrides();
        xOver.Add(typeof(Foo), "Bars", new XmlAttributes {
            XmlArray = new XmlArrayAttribute("Bars"),
            XmlArrayItems = {
                new XmlArrayItemAttribute("SomethingElse", typeof(Bar))
            }
        });
        XmlSerializer serializer = new XmlSerializer(typeof(Foo), xOver);
        using (var writer = new StringWriter()) {
            Foo foo = new Foo { Bars = new List<Bar> {
                new Bar { Widget = "widget"}
            }};
            serializer.Serialize(writer, foo);
            string xml = writer.ToString();
        }
    }
}

这篇关于如何使用XmlAttributeOverrides集合元素重写XML元素名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 10:36