遵循LINQ-to-XML原理,从生成的XML文档中省略可选属性 [英] Omitting optional attributes from generated XML document, following LINQ-to-XML philosophy

查看:120
本文介绍了遵循LINQ-to-XML原理,从生成的XML文档中省略可选属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用LINQ to XML生成XML文档文档.我希望XML文档最小,即很少使用的属性应省略.目前,我正在这样做:

I am generating XML documents documents using LINQ to XML. I want the XML document to be minimal, i.e. seldom used properties should be omitted. Currently, I am doing it like this:

XElement element = new XElement("myelement",
        new XAttribute("property1", value1),
        new XAttribute("property2", value2));
if (!string.IsNullOrEmpty(rareValue1))
{
    element.Add(new XAttribute("rareProperty1", rareValue1));
}
if (!string.IsNullOrEmpty(rareValue2))
{
    element.Add(new XAttribute("rareProperty2", rareValue2));
}
if (!string.IsNullOrEmpty(rareValue3))
{
    element.Add(new XAttribute("rareProperty3", rareValue3));
}

但是实际上,if想要省略"if"语句,因为它们不是很优雅,并且与LINQ to XML原理相矛盾,在LINQ to XML原理中,您可以如

But actually, if would like to omit the "if"-statements, because they are not very elegant and they contradict the LINQ to XML philosophy where you can easily create XML trees by nesting as described in Creating Trees in XML. So, I would like to do something like this:

XElement element = new XElement("myelement",
        new XAttribute("property1", value1),
        new XAttribute("property2", value2),
        new XAttribute("rareProperty1", string.IsNullOrEmpty(rareValue1) ? Flag.Omit : rareValue1),
        new XAttribute("rareProperty2", string.IsNullOrEmpty(rareValue2) ? Flag.Omit : rareValue1),
        new XAttribute("rareProperty3", string.IsNullOrEmpty(rareValue3) ? Flag.Omit : rareValue1),
);

即C#源代码在其构造函数中包含myelement的所有子属性. Flag.Omit是指示LINQ-to-XML不要生成XML属性的某种方式.

I.e. the C# source code contains all child attributes of myelement inside its constructor. And Flag.Omit would be some way to instruct LINQ-to-XML not to generate an XML attribute.

使用标准LINQ to XML或某些通用实用程序功能是否可能?

Is this possible with standard LINQ to XML or with some generic utility function?

推荐答案

添加子节点的各种方法都忽略了null值-因此,您所需要的只是一个辅助方法:

The various ways of adding child nodes all ignore null values - so all you need is a helper method:

public static XAttribute AttributeOrNull(XName name, string value)
{
    return string.IsNullOrEmpty(value) ? null : new XAttribute(name, value);
}

然后:

XElement element = new XElement("myelement",
        new XAttribute("property1", value1),
        new XAttribute("property2", value2),
        AttributeOrNull("rareProperty1", rareValue1),
        AttributeOrNull("rareProperty2", rareValue2),
        AttributeOrNull("rareProperty3", rareValue3)
);

这篇关于遵循LINQ-to-XML原理,从生成的XML文档中省略可选属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆