次の XElement があります。
<Assembly name="3">
<Component name="2" />
</Assembly>
ルート要素だけを取得したいと思います。 <Assembly name="3">
自分に合った方法が見つかりません。
XElement.????? I cant find XElement.Root;
手がかりはありますか?
VB.NETでこれを試すことができます
Dim elm as XElment = XElement.Parse(<Assembly name="3">
<Component name="2" />
</Assembly>)
Dim strName as string
strName = elm.AncestorsAndSelf.First.Name
C# でのコード
XElement elm = XElement.Parse("<Assembly name='3'><Component name='2' /></Assembly>");
string name =elm.AncestorsAndSelf().First().Name;
次の方法でルート要素を取得できます。
XDocument.Root
実装例を次に示します。
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
他の理由で元のコンテンツを保持する必要RemoveNodes
がある場合は、最初にコピーを作成してください。
これで何をしようとしているのかは明確ではありません。要素には、そのすべての子が論理的に含まれていますXElement.Root
。要素が「それ自体」であるという概念はありません。RemoveNodes
すべての子ノードを削除しますが、要素の名前またはその属性を取得したいだけの場合は、構造をまったく変更せずにそれを行うことができます。
名前と属性を新しい要素にコピーします。
var root = new XElement(el.Name, el.Attributes());