2

次の XElement があります。

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

ルート要素だけを取得したいと思います。 <Assembly name="3">自分に合った方法が見つかりません。

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

手がかりはありますか?

4

4 に答える 4

4

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;
于 2012-08-27T10:35:35.143 に答える
2

次の方法でルート要素を取得できます。

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

于 2012-06-15T12:44:59.303 に答える
0

他の理由で元のコンテンツを保持する必要RemoveNodesがある場合は、最初にコピーを作成してください。

これで何をしようとしているのかは明確ではありません。要素には、そのすべての子が論理的に含まれていますXElement.Root。要素が「それ自体」であるという概念はありません。RemoveNodesすべての子ノードを削除しますが、要素の名前またはその属性を取得したいだけの場合は、構造をまったく変更せずにそれを行うことができます。

于 2012-06-15T12:45:09.220 に答える
-1

名前と属性を新しい要素にコピーします。

var root = new XElement(el.Name, el.Attributes());
于 2014-08-15T11:19:13.817 に答える