Partilhar via


Adicionando elementos, atributos e os nós a uma árvore XML

Você pode adicionar conteúdo (elementos, atributos, comentários, instruções de processamento, texto e CDATA) a uma árvore XML existente.

Métodos para adicionar conteúdo

Os seguintes métodos adicionam conteúdo filho a um XElement ou a um XDocument:

Método

Descrição

Add

Adiciona conteúdo ao final do conteúdo filho de XContainer.

AddFirst

Adiciona conteúdo ao início do conteúdo filho de XContainer.

Os seguintes métodos adicionam o conteúdo como nós irmãos de um XNode. O nó mais comum ao qual você adiciona conteúdo irmão é XElement, embora você possa adicionar conteúdo irmão válido a outros tipos de nós como XText ou XComment.

Método

Descrição

AddAfterSelf

Adiciona conteúdo depois de XNode.

AddBeforeSelf

Adiciona conteúdo antes de XNode.

Exemplo

Descrição

O exemplo a seguir cria duas árvores XML e, em seguida, modifica uma das árvores.

Código

XElement srcTree = new XElement("Root", 
    new XElement("Element1", 1),
    new XElement("Element2", 2),
    new XElement("Element3", 3),
    new XElement("Element4", 4),
    new XElement("Element5", 5)
);
XElement xmlTree = new XElement("Root",
    new XElement("Child1", 1),
    new XElement("Child2", 2),
    new XElement("Child3", 3),
    new XElement("Child4", 4),
    new XElement("Child5", 5)
);
xmlTree.Add(new XElement("NewChild", "new content"));
xmlTree.Add(
    from el in srcTree.Elements()
    where (int)el > 3
    select el
);
// Even though Child9 does not exist in srcTree, the following statement will not
// throw an exception, and nothing will be added to xmlTree.
xmlTree.Add(srcTree.Element("Child9"));
Console.WriteLine(xmlTree);
Dim srcTree As XElement = _
    <Root>
        <Element1>1</Element1>
        <Element2>2</Element2>
        <Element3>3</Element3>
        <Element4>4</Element4>
        <Element5>5</Element5>
    </Root>
Dim xmlTree As XElement = _
    <Root>
        <Child1>1</Child1>
        <Child2>2</Child2>
        <Child3>3</Child3>
        <Child4>4</Child4>
        <Child5>5</Child5>
    </Root>

xmlTree.Add(<NewChild>new content</NewChild>)
xmlTree.Add( _
    From el In srcTree.Elements() _
    Where CInt(el) > 3 _
    Select el)

' Even though Child9 does not exist in srcTree, the following statement
' will not throw an exception, and nothing will be added to xmlTree.
xmlTree.Add(srcTree.Element("Child9"))
Console.WriteLine(xmlTree)

Comentários

Esse código gera a seguinte saída:

<Root>
  <Child1>1</Child1>
  <Child2>2</Child2>
  <Child3>3</Child3>
  <Child4>4</Child4>
  <Child5>5</Child5>
  <NewChild>new content</NewChild>
  <Element4>4</Element4>
  <Element5>5</Element5>
</Root>

Consulte também

Outros recursos

Modificando árvores XML (LINQ to XML)