2012-06-15 54 views
0

得到的只是根元素,我有以下的XElement:如何從的XElement

<Assembly name="3"> 
    <Component name="2" /> 
</Assembly> 

我希望得到公正的根元素。 <Assembly name="3">我不能看到適合我的任何方法。

XElement.????? I cant find XElement.Root; 

有什麼線索嗎?

+0

你想用元素做什麼? –

回答

1

你可以調用它RemoveNodes ...先創建一個副本,如果你需要保存其他原因的原創內容。

這是不是很清楚你想要做什麼。元素在邏輯上包含了所有的子元素 - 沒有XElement.Root的概念,因爲元素「本身」。 RemoveNodes將刪除所有子節點,但如果只想獲取元素的名稱或其屬性,則可以在不更改結構的情況下執行此操作。

+0

我在Linq-Query中找到了這個Xelement。然後我需要將另一個Xelement插入到這個... -...編輯中。哇,我可以插入另一個XElement無需提取根。 我找到了答案。謝謝!!!! – kmxillo

+1

@kmxillo:所以只需調用'element.Add(extraElement)'。爲什麼你需要先剝離它?給你的問題添加上下文會有很大的幫助。 –

0

這可能是一個辦法:

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()); 

鏈接:http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.root.aspx

+0

Skeet的答案更容易實現。謝謝 – kmxillo

3

您可以在C#中嘗試這種在VB.NET

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; 
0

複製&屬性將新元素的名稱;

var root = new XElement(el.Name, el.Attributes());