<UserModel xmlns="http://tempuri.org/">
<Name>Liu</Name>
<Age>23</Age>
</UserModel>怎么用linq to xml 查询把上面的一个字符串 投影成一个匿名类??如果可以的话 与实体类对应,假如存在一个UserModel类,并包含Name和Age两个字段····
<Name>Liu</Name>
<Age>23</Age>
</UserModel>怎么用linq to xml 查询把上面的一个字符串 投影成一个匿名类??如果可以的话 与实体类对应,假如存在一个UserModel类,并包含Name和Age两个字段····
{
// Create an anonymous array of anonymous types.
var data = new [] {
new { PetName = "Melvin", ID = 10 },
new { PetName = "Pat", ID = 11 },
new { PetName = "Danny", ID = 12 },
new { PetName = "Clunker", ID = 13 }
};
// Now enumerate over the array to build
// an XElement.
XElement vehicles =
new XElement("Inventory",
from c in data
select new XElement("Car",
new XAttribute("ID", c.ID),
new XElement("PetName", c.PetName)
)
);
Console.WriteLine(vehicles);
}想楼主说的这样,你是想让Name和Age这两个字段成为属性吧,是这个我也没有用过,但是可以自己封装!
string path2 = @"c:\test.xml";
var xdoc2 = XDocument.Load(path2);
var col2 = from x in xdoc2.Descendants() where x.Name.LocalName != "UserModel" select new KeyValuePair<string, string>(x.Name.LocalName, x.Value); IList<UserModel> list = new List<UserModel>(); //如果只有一个用户实体·取消FOR循环
for (int i = 0; i < col2.Count() / 2; i++)
{
UserModel um = new UserModel();
foreach (var item in col2)
{
if (item.Key == "Name")
{
um.Name = item.Value;
} if (item.Key == "Age")
{
um.Age = item.Value;
}
}
if (um != null)
{
list.Add(um);
}
}
public class UserModel
{
public string Name { get; set; } public string Age { get; set; } }
<ArrayOfModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
奇怪为什么如果加上了上面的命名空间,则我在查询的时候用Descendants("")却查不出来呢?如果去掉了上命名空间,就可以用Descendants("")查询出来了这是怎么回事呢?