I have a similar scenario as this one:
我有一个类似的场景:
public class TestLinq2Xml
{
private XElement GenerateSomeXml()
{
return XElement.Parse(@"<MyObject>
<Properties>
<Name>My object 1</Name>
<Position>0; 0; 0</Position>
</Properties>
</MyObject>");
}
public void ExploreXmlNode()
{
var xmlTree = this.GenerateSomeXml();
var name = xmlTree.Element("MyObject").Element("Properties").Element("Name").Value;
Console.WriteLine(name);
}
}
}
Ok, this is very simplified. ....but it still wont work. Any ideas on what I'm doing wrong here?
好吧,这很简单。....但它仍然不起作用。有什么想法吗?
Edit:
编辑:
Oh, almost forgot. The problem is that xmlTree.Element("MyObject")
returns an empty linq sequence. Even though I clearly have a node named "MyObject".
哦,差点忘了。问题是xmlTree.Element(“MyObject”)返回一个空的linq序列。尽管我有一个名为“MyObject”的节点。
2 个解决方案
#1
3
The XElement.Parse returns an XElement which is the <MyObject>
node. Try:-
XElement。Parse返回一个XElement,它是< object >节点。试一试:
var name = xmlTree.Element("Properties").Element("Name").Value;
var name = xmlTree.Element(“属性”).Element value(“名字”);
#2
2
Besides what the previous poster suggested, you can also return an XDocument from your GenerateSomeXml() function so that your linq works.
除了前面的海报建议的之外,您还可以从GenerateSomeXml()函数返回一个XDocument,以便您的linq能够工作。
private static XDocument GenerateSomeXml()
{
return XDocument.Parse(@"<MyObject>
<Properties>
<Name>My object 1</Name>
<Position>0; 0; 0</Position>
</Properties>
</MyObject>");
}
#1
3
The XElement.Parse returns an XElement which is the <MyObject>
node. Try:-
XElement。Parse返回一个XElement,它是< object >节点。试一试:
var name = xmlTree.Element("Properties").Element("Name").Value;
var name = xmlTree.Element(“属性”).Element value(“名字”);
#2
2
Besides what the previous poster suggested, you can also return an XDocument from your GenerateSomeXml() function so that your linq works.
除了前面的海报建议的之外,您还可以从GenerateSomeXml()函数返回一个XDocument,以便您的linq能够工作。
private static XDocument GenerateSomeXml()
{
return XDocument.Parse(@"<MyObject>
<Properties>
<Name>My object 1</Name>
<Position>0; 0; 0</Position>
</Properties>
</MyObject>");
}