如何在xml中将空格从.net LINQ显示为数据表中的XML

时间:2014-08-07 03:17:10

标签: xml linq

如果元素在XML中为空,我试图不显示该元素。我有以下代码

XDocument doc =  new XDocument(
                new XDeclaration("1.0", "UTF-8", "yes"),
                new XElement("products", 
                    from p in ds.Tables[0].AsEnumerable()
                    select new XElement("ORDER",
                        new XElement("TYPE", p["LetterType"]),
                        new XElement("SUBTYPE", p["LetterSubType"]),
                        new XElement("ID_1", p["ID1"]),
                        new XElement("ID_2", p["ID2"]),
                        new XElement("ID_3", p["ID3"]),
                        new XElement("STATUS_DETAIL",
                            new XElement("STATUS", p["Status"]),
                            new XElement("STATUS_DATE", p["StatusDate"]),
                            new XElement("LANGUAGE", p["Language"])))));

XML出现如下

<ORDER>
    <TYPE>XYZ</TYPE>
    <SUBTYPE>ABC</SUBTYPE>
    <ID_1>ID123456</ID_1>
    <ID_2></ID_2>
    <ID_3></ID_3>
    <STATUS_DETAIL>
      <STATUS>N</STATUS>
      <STATUS_DATE>2014-08-04T13:37:54.33</STATUS_DATE>
      <LANGUAGE>01</LANGUAGE>
    </STATUS_DETAIL>
  </ORDER>

我不希望ID_2,ID_3显示在XML中,因为它们是空的。我怎样才能做到这一点? 感谢

1 个答案:

答案 0 :(得分:0)

您可以在添加XElement之前添加一个简单的检查:

XDocument doc =  new XDocument(
    new XDeclaration("1.0", "UTF-8", "yes"),
        new XElement("products", 
            from p in ds.Tables[0].AsEnumerable()
            select new XElement("ORDER",
                new XElement("TYPE", p["LetterType"]),
                new XElement("SUBTYPE", p["LetterSubType"]),
                !String.IsNullOrEmpty(p["ID1"].ToString()) ? new XElement("ID_1", p["ID1"]) : null,
                !String.IsNullOrEmpty(p["ID2"].ToString()) ? new XElement("ID_2", p["ID2"]) : null,
                !String.IsNullOrEmpty(p["ID3"].ToString()) ? new XElement("ID_3", p["ID3"]) : null,
                new XElement("STATUS_DETAIL",
                    new XElement("STATUS", p["Status"]),
                    new XElement("STATUS_DATE", p["StatusDate"]),
                    new XElement("LANGUAGE", p["Language"])))));