我有以下XElement:
<Assembly name="3">
<Component name="2" />
</Assembly>
我只想获取根元素。 <Assembly name="3">
我看不到任何适合我的方法。
XElement.????? I cant find XElement.Root;
有什么线索吗?
如果需要出于其他原因保留原始内容,则可以在其上调用RemoveNodes
...首先创建副本。
尚不清楚您打算如何处理。元素在逻辑上包含其所有子元素-因为元素“本身”所以没有RemoveNodes
的概念。 XElement.Root
将删除所有子节点,但是如果您只想获取元素的名称或其属性,则可以完全不更改其结构。
您可以在VB.NET中尝试此操作
RemoveNodes
C#中的代码
Dim elm as XElment = XElement.Parse(<Assembly name="3">
<Component name="2" />
</Assembly>)
Dim strName as string
strName = elm.AncestorsAndSelf.First.Name
这可能是一种方法:
XElement elm = XElement.Parse("<Assembly name='3'><Component name='2' /></Assembly>");
string name =elm.AncestorsAndSelf().First().Name;
链接:XDocument doc = new XDocument(
new XComment("This is a comment."),
new XElement("Pubs",
new XElement("Book",
new XElement("Title", "Artifacts of Roman Civilization"),
new XElement("Author", "Moreno, Jordao")
),
new XElement("Book",
new XElement("Title", "Midieval Tools and Implements"),
new XElement("Author", "Gazit, Inbar")
)
),
new XComment("This is another comment.")
);
Console.WriteLine(doc.Root.Name.ToString());