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

linq to xml xml文档中节点不是成对的问题
XML code
<?xml version="1.0" encoding="utf-8"?>
<root return="0" info="成功" msgid="F830DBA1777415B9" numbers="1" messages="1"/>


上面是我获取到的xml,但是不是如下形式<root></root>,我写了如下代码 报错出现非法字符,linq to xml难道只能读取成对节点的xml字符串吗?

------解决方案--------------------
如果文档不符合XML标准,改用传统的SelectSingleNode试试
------解决方案--------------------
C# code

void Main()
{    
string str = @"<?xml version=""1.0"" encoding=""utf-8""?>
<root return=""0"" info=""成功"" msgid=""F830DBA1777415B9"" numbers=""1"" messages=""1""/>";
  var data=XDocument.Parse(str);

  var query=from x in data.Descendants("root")   
            select  new
            {
                x.Attribute("msgid").Value 
            };
       Console.WriteLine(query.First().Value);  //F830DBA1777415B9
 
}

------解决方案--------------------
C# code

//用LOAD也木有发现有什么问题
void Main()
{    
  var data=XDocument.Load("C:\\test.xml");

  var query=from x in data.Descendants("root")   
            select  new
            {
                x.Attribute("msgid").Value 
            };
       Console.WriteLine(query.First().Value);  //F830DBA1777415B9
 
}