linq to sql / xml - 为链接表生成xml

时间:2010-11-05 13:37:44

标签: sql xml linq

我有很多有很多列的表,想要使用linq 生成xml而不必指定 列名。这是一个简单的例子:

users
---------------
user_id
name
email

user_addresses
---------------
address_id
user_id
city
state

这是我想用linq生成的xml看起来像

<user>
 <name>john</name>
 <email>john@dlsjkf.com</email>
 <address>
  <city>charleston</city>
  <state>sc</state>
 </address>
 <address>
  <city>charlotte</city>
  <state>nc</state>
 </address>
</user>

所以我猜测代码看起来像这样:

var userxml = new XElement("user",
 from row in dc.Users where user.id == 5
 select (what do i put here??)
 );

我可以为一个表执行此操作,但无法弄清楚如何为链接表生成xml(如user_addresses)。

任何想法?

2 个答案:

答案 0 :(得分:1)

确定找到了一种方法来获取我想要的xml,但是我必须在查询中指定相关的表名...这对我现在的猜测已经足够了。这是代码:

XElement root = new XElement("root",
    from row in dc.users
    where row.user_id == 5
    select new XElement("user",
        row.AsXElements(),
        new XElement("addresses",
            from row2 in dc.user_addresses
            where row2.user_id == 5
            select new XElement("address", row2.AsXElements())
        )
    )
);


// used to generate xml tags/elements named after the table column names
public static IEnumerable<XElement> AsXElements(this object source)
{
  if (source == null) throw new ArgumentNullException("source");

  foreach (System.Reflection.PropertyInfo prop in source.GetType().GetProperties())
  {
    object value = prop.GetValue(source, null);

    if (value != null)
    {
      bool isColumn = false;

      foreach (object obj in prop.GetCustomAttributes(true))
      {
        System.Data.Linq.Mapping.ColumnAttribute attribute = obj as System.Data.Linq.Mapping.ColumnAttribute;
        if (attribute != null)
        {
          isColumn = true;
          break;
        }
      }

      if (isColumn)
      {
        yield return new XElement(prop.Name, value);
      }
    }
  }
}

答案 1 :(得分:0)

您需要使用联接。这是一种方式:

var query = from user in dc.Users
            from addr in dc.UserAddress
            where user.Id == addr.UserId
            select new XElement("user",
                new XElement("name", user.Name),
                new XElement("email", user.Email), 
                new XElement("address",
                    new XElement("city", addr.City),
                    new XElement("state", addr.State)));

foreach (var item in query)
    Console.WriteLine(item);
  

我有很多桌子   列并希望使用生成xml   linq无需指定   专栏名称。

不太确定如何实现这一目标。您需要说明进入XML的列名。即使您要反映字段名称,如何在不指定列名的情况下过滤掉不需要的字段并正确构造它们?例如,您将如何设置地址部分?您可以在UserUserAddressUser.GetType().GetFields()上使用此字段来获取字段,然后浏览每个字段的Name,然后查看内容是什么?

相关问题