日期:2014-05-20  浏览次数:20796 次

linq to xml 能读xml类型的字符串吗
linq to xml 能读xml类型的字符串吗,比如我通过HttpWebRequest得到了一个装有xml的字符串 我能直接load他吗

------解决方案--------------------
当然能,XML本质就是字符串...那些XmlDocument之类的只不过是容器而已...
------解决方案--------------------
转换 一下 就行。XElement.Parse(" ");
------解决方案--------------------
当然可以
帖个DEMO:

C# code

void Main()
{    
string str = "<Info><state>待命</state><WId>000028532</WId><BillState>装货中</BillState><Driver>陈靖彩</Driver><items><item><Consignor>利源煤灰</Consignor><Consignee>阿海电站</Consignee>" +
                    "<LoadLocation>利源煤灰</LoadLocation><UnloadLocation>水电七局</UnloadLocation><GoodName>煤灰</GoodName><GoodsBreed>II 级灰</GoodsBreed><GoodPack>散装</GoodPack><Send>0.0000</Send>" +
                    "<Recive>0.0000</Recive></item></items><items><item><Consignor>利源煤灰1</Consignor><Consignee>阿海电站1</Consignee><LoadLocation>利源煤灰1</LoadLocation><UnloadLocation>水电七局1</UnloadLocation>" +
                    "<GoodName>煤灰1</GoodName><GoodsBreed>II 级灰1</GoodsBreed><GoodPack>散装1</GoodPack><Send>0.0000</Send><Recive>0.0000</Recive></item></items><items><item><Consignor>利源煤灰2</Consignor>" +
                    "<Consignee>阿海电站2</Consignee><LoadLocation>利源煤灰2</LoadLocation><UnloadLocation>水电七局2</UnloadLocation><GoodName>煤灰2</GoodName><GoodsBreed>II 级灰2</GoodsBreed><GoodPack>散装2</GoodPack>" +
                    "<Send>0.0000</Send><Recive>0.0000</Recive></item></items></Info>";
  var data=XElement.Parse(str);
   
  var query=from x in data.Descendants("items")   
            select new
            {
                state=x.Parent.Element("state").Value,
                WId =x.Parent.Element("WId").Value,
                BillState =x.Parent.Element("BillState").Value,
                Driver=x.Parent.Element("Driver").Value,
                Consignor=x.Element("item").Element("Consignor").Value,
                Consignee =x.Element("item").Element("Consignee").Value,
                LoadLocation =x.Element("item").Element("LoadLocation").Value,
                UnloadLocation =x.Element("item").Element("UnloadLocation").Value,
                GoodName   =x.Element("item").Element("GoodName").Value
            };
 query.ToList().ForEach(q=>Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t",q.state,q.WId,q.BillState,q.Driver,q.Consignor,q.Consignee,q.LoadLocation,q.UnloadLocation,q.GoodName));
 /*
 待命    000028532    装货中    陈靖彩    利源煤灰    阿海电站    利源煤灰    水电七局    煤灰    
待命    000028532    装货中    陈靖彩    利源煤灰1    阿海电站1    利源煤灰1    水电七局1    煤灰1    
待命    000028532    装货中    陈靖彩    利源煤灰2    阿海电站2    利源煤灰2    水电七局2    煤灰2
 */
}