xml条件XElement创建

时间:2013-06-12 01:47:48

标签: c# xml

我构建了这个xml文件:

   var persons = new[] {
   new Person {
      Name = "Patrick Hines",
      PhoneNumbers = new[] { "206-555-0144", "425-555-0145" }
   },
   new Person {
      Name = "Gretchen Rivas",
      PhoneNumbers = new[] { "206-555-0163" }
   }
};
            XElement contacts =
               new XElement("contacts",
                  from p in persons
                  where p.Name.StartsWith("G")
                  select new XElement("contact",
                     new XElement("name", p.Name),
                     from ph in p.PhoneNumbers
                     select new XElement("phone", ph)
                  )
               );


        class Person
        {
            public string Name;
            public string[] PhoneNumbers;
        }

在此示例中,phonenumber不为空。当电话号码字符串为空或为空时,如何编码它不会在我的xml中创建元素?

1 个答案:

答案 0 :(得分:0)

从PhoneNumbers过滤掉空字符串和空字符串:

   from ph in p.PhoneNumbers where !String.IsNullOrEmpty(ph)