다음을 통해 공유


XML 트리에 요소, 특성 및 노드 추가

업데이트: November 2007

내용(요소, 특성, 주석, 처리 명령, 텍스트 및 CDATA)을 기존 XML 트리에 추가할 수 있습니다.

내용을 추가하는 메서드

다음 메서드는 자식 내용을 XElement 또는 XDocument에 추가합니다.

메서드

설명

Add

XContainer의 자식 내용 끝 부분에 내용을 추가합니다.

AddFirst

XContainer의 자식 내용 시작 부분에 내용을 추가합니다.

다음 메서드는 XNode의 형제 노드로 내용을 추가합니다. 유효한 형제 내용을 XText 또는 XComment와 같은 다른 형식의 노드에 추가할 수 있지만, 형제 내용을 추가할 가장 일반적인 노드는 XElement입니다.

메서드

설명

AddAfterSelf

XNode 뒤에 내용을 추가합니다.

AddBeforeSelf

XNode 앞에 내용을 추가합니다.

예제

설명

다음 예제에서는 두 가지 XML 트리를 만든 다음 두 트리 중 하나를 수정합니다.

코드

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)

설명

이 코드의 결과는 다음과 같습니다.

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

참고 항목

기타 리소스

XML 트리 수정(LINQ to XML)