【问题标题】:Linq to XML - Create Xelement only IF somethingLinq to XML - 仅在某些情况下创建 Xelement
【发布时间】:2013-01-28 15:58:22
【问题描述】:

我是 linq to xml 的新手,并尝试执行以下操作。 我正在从我收到的一些对象中创建一个新的 xml。

我有一个名为“Scale”的 XElement 有一个布尔值“DynamicScale”,如果是False,我需要创建两个XElements作为Scale的后代,如果是True,我不需要这些元素。

  <Scale DynamicScale="False">
    <LowScale>0</LowScale>
    <HighScale>10000</HighScale>
  </Scale>

有没有办法在这个创建过程中添加If 语句? 或任何其他建议来处理这种需求? 如果我想能够做到这一点(我知道这是不可能的)。欢迎任何简单的方法。

new XElement("Scale",
    new XAttribute("DynamicScale", c.DynamicScale),
    if (c.DynamicScale == false)
    {
        new XElement("LowScale", c.LowScale),
        new XElement("HighScale", c.HighScale),
    })

【问题讨论】:

    标签: xml linq linq-to-xml


    【解决方案1】:

    使用ternary operator

    new XElement(
        "Scale",
        new XAttribute("DynamicScale", c.DynamicScale), 
        c.DynamicScale ? 
            null: 
            new[]
            { 
                new XElement("HighScale", c.HighScale),
                new XElement("LowScale", c.LowScale)
            }
    );
    

    【讨论】:

    • 感谢您的快速响应
    【解决方案2】:
    new XElement("Scale",
         new XAttribute("DynamicScale",  c.DynamicScale),
         c.DynamicScale ? null : new XElement("LowScale", c.LowScale),
         c.DynamicScale ? null : new XElement("HighScale", c.HighScale));
    

    对于非动态比例,这将产生

      <Scale DynamicScale="False">
        <LowScale>0</LowScale>
        <HighScale>10000</HighScale>
      </Scale>
    

    动态比例

      <Scale DynamicScale="True"/>
    

    或更短的版本:

    new XElement("Scale",
         new XAttribute("DynamicScale",  c.DynamicScale),
         c.DynamicScale ? null : new XElement[] {
                      new XElement("LowScale", c.LowScale),
                      new XElement("HighScale", c.HighScale) }
         );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2020-06-20
      • 2015-05-02
      • 2018-05-21
      • 2016-11-04
      • 1970-01-01
      相关资源
      最近更新 更多