XML删除nil属性

时间:2014-12-11 07:31:21

标签: c# xml nullable null

我正在做一些XmlOverrides并将属性设置为nullable(在本例中为F1)。我想删除nil =“true”和该属性周围的命名空间,但我不能用我尝试过的任何方法删除它。

Nested n = new Nested();
n.Nest = "2";
n.F1 = null;

XmlAttributeOverrides overrides = new XmlAttributeOverrides();

XmlAttributes att = new XmlAttributes();
XmlElementAttribute el = new XmlElementAttribute("F1");
el.IsNullable = true;
att.XmlElements.Add(el);
overrides.Add(typeof(Nested), "F1", att);

XmlSerializer xs = new XmlSerializer(typeof(Nested), overrides);

var faultDocument = new XmlDocument();
var nav = faultDocument.CreateNavigator();
var ns = new XmlSerializerNamespaces();
ns.Add("", "");

using (var writer = nav.AppendChild())
{
    xs.Serialize(writer, n, ns);
}

我得到的XML是这样的:

<Nested>
    <F1 p2:nil="true" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance"/>
    <Nest>2</Nest>
</Nested>

但是我希望F1元素为空,没有nil和xmlns

<Nested>
    <F1/>
    <Nest>2</Nest>
</Nested>

3 个答案:

答案 0 :(得分:0)

尝试在属性F1中添加嵌套类[XmlElement(ElementName = "F1", IsNullable = true)]

答案 1 :(得分:0)

我设法解决了它,不确定它是否是最好的方法:

private static void RemoveNils(XElement elem)
{
        string nilNamespace = "{http://www.w3.org/2001/XMLSchema-instance}nil";
        //first condition should be enough, the rest are just fail-safes
        if (elem.Attributes().Any(name => name.Name == nilNamespace) && elem.Elements().Count() == 0 && elem.IsEmpty)
        {
            elem.Attributes().Remove();
            return;
        }

        foreach (XElement el in elem.Elements())
            RemoveNils(el);

}

答案 2 :(得分:-1)

试试这个

Nested n = new Nested();
n.Nest = "2";
n.F1 = null;

XmlAttributeOverrides overrides = new XmlAttributeOverrides();

XmlAttributes att = new XmlAttributes();
XmlElementAttribute el = new XmlElementAttribute("F1");
el.IsNullable = true;
att.XmlElements.Add(el);
overrides.Add(typeof(Nested), "F1", att);

XmlSerializer xs = new XmlSerializer(typeof(Nested));

var faultDocument = new XmlDocument();
var nav = faultDocument.CreateNavigator();
StringWriter strWriter = new StringWriter();
XmlTextWriter TextWriter = new XmlTextWriter(strWriter);
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
xs.Serialize(TextWriter, n, ns);
ReqXml = strWriter.ToString();
TextWriter.Close();
return ReqXml;