C# Can';t将xml读入<&燃气轮机;使用linq,获取空值
我有一个XML文件:C# Can';t将xml读入<&燃气轮机;使用linq,获取空值,c#,linq-to-xml,C#,Linq To Xml,我有一个XML文件: <?xml version="1.0" encoding="us-ascii"?> <TestItems xmlns="http://www.blogger.com"> <TestItem correct="0" incorrect="0"> <Question>question</Question> <Answer>answer</Answer> <Tag
<?xml version="1.0" encoding="us-ascii"?>
<TestItems xmlns="http://www.blogger.com">
<TestItem correct="0" incorrect="0">
<Question>question</Question>
<Answer>answer</Answer>
<Tags>test1;test2</Tags>
</TestItem>
<TestItem correct="0" incorrect="0">
<Question>question3</Question>
<Answer>answer3</Answer>
<Tags>tagA;tagB;tagC</Tags>
</TestItem>
</TestItems>
下面是我用来将数据读入内存的代码:
XDocument ktdb = XDocument.Load("KTdb.xml");
XNamespace ns = ktdb.Root.Name.Namespace;
var testItems = from item in ktdb.Descendants(ns + "TestItem")
select new TestItem
{
Question = item.Element(ns + "Question").Value,
Answer = (string)item.Element(ns + "Answer").Value,
Tags = item.Element(ns + "Tags").Value,
NumberCorrect = Convert.ToInt32(item.Attribute(ns + "correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute(ns + "incorrect").Value)
};
但它不会让我这么做。当执行LINQ语句时,对TestItem对象调用默认构造函数,然后我得到null异常,因为item.Element(ns+“Question”).Value
为null
为什么我会出错?如何修复代码
谢谢。更改此选项:
NumberCorrect = Convert.ToInt32(item.Attribute(ns + "correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute(ns + "incorrect").Value)
为此:
NumberCorrect = Convert.ToInt32(item.Attribute("correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute("incorrect").Value)
i、 e.从属性名称中删除ns的串联
NumberCorrect = Convert.ToInt32(item.Attribute("correct").Value),
NumberIncorrect = Convert.ToInt32(item.Attribute("incorrect").Value)