XmlDocument 클래스

정의

XML 문서를 나타냅니다. 이 클래스를 사용하여 문서에서 XML을 로드, 유효성 검사, 편집, 추가 및 배치할 수 있습니다.

public ref class XmlDocument : System::Xml::XmlNode
public class XmlDocument : System.Xml.XmlNode
type XmlDocument = class
    inherit XmlNode
Public Class XmlDocument
Inherits XmlNode
상속
XmlDocument
파생

설명

클래스는 XmlDocument XML 문서의 메모리 내 표현입니다. W3C XML DOM(문서 개체 모델) 수준 1 코어와 코어 DOM 수준 2를 구현합니다.

DOM문서 개체 모델을 의미합니다. 자세한 내용은 XML DOM(문서 개체 모델)을 참조하세요.

클래스를 사용하여 XmlDocument XML을 DOM에 로드한 다음 문서에서 XML을 프로그래밍 방식으로 읽고 수정하고 제거할 수 있습니다.

클래스를 열고 XmlDocument 구현 방법을 확인하려면 참조 원본을 참조하세요.

문서 개체 모델에 XML 로드

컬렉션에 몇 권의 책이 있는 XML 문서로 시작합니다. 여기에는 네임스페이스, 데이터를 나타내는 요소 및 데이터를 설명하는 특성을 포함하여 XML 문서에서 찾을 수 있는 기본 항목이 포함되어 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<books xmlns="http://www.contoso.com/books">
  <book genre="novel" ISBN="1-861001-57-8" publicationdate="1823-01-28">
    <title>Pride And Prejudice</title>
    <price>24.95</price>
  </book>
  <book genre="novel" ISBN="1-861002-30-1" publicationdate="1985-01-01">
    <title>The Handmaid's Tale</title>
    <price>29.95</price>
  </book>
  <book genre="novel" ISBN="1-861001-45-3" publicationdate="1811-01-01">
    <title>Sense and Sensibility</title>
    <price>19.95</price>
  </book>
</books>

다음으로, 메모리에서 작업할 수 있도록 이 데이터를 DOM에 로드합니다. 이 작업을 수행하는 가장 인기 있는 방법은 로컬 컴퓨터 또는 네트워크의 파일을 참조하는 것입니다.

이 예제에서는 파일에서 XML을 로드합니다. 파일이 없으면 일부 XML만 생성하여 로드합니다.

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
try { doc.Load("booksData.xml"); }
catch (System.IO.FileNotFoundException)
{
    doc.LoadXml("<?xml version=\"1.0\"?> \n" +
    "<books xmlns=\"http://www.contoso.com/books\"> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
    "    <title>Pride And Prejudice</title> \n" +
    "    <price>24.95</price> \n" +
    "  </book> \n" +
    "  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
    "    <title>The Handmaid's Tale</title> \n" +
    "    <price>29.95</price> \n" +
    "  </book> \n" +
    "</books>");
}
Dim doc As XmlDocument = New XmlDocument
doc.PreserveWhitespace = True
Try
    doc.Load("booksData.xml")
Catch ex As System.IO.FileNotFoundException
    ' If no file is found, generate some XML.
    doc.LoadXml("<?xml version=""1.0""?> " & ControlChars.NewLine & _
        "<books xmlns=""http://www.contoso.com/books""> " & ControlChars.NewLine & _
        "  <book genre=""novel"" ISBN=""1-861001-57-8"" publicationdate=""1823-01-28""> " & ControlChars.NewLine & _
        "    <title>Pride And Prejudice</title> " & ControlChars.NewLine & _
        "    <price>24.95</price> " & ControlChars.NewLine & _
        "  </book> " & ControlChars.NewLine & _
        "  <book genre=""novel"" ISBN=""1-861002-30-1"" publicationdate=""1985-01-01""> " & ControlChars.NewLine & _
        "    <title>The Handmaid's Tale</title> " & ControlChars.NewLine & _
        "    <price>29.95</price> " & ControlChars.NewLine & _
        "  </book> " & ControlChars.NewLine & _
        "</books>")
End Try

자세한 내용은 DOM에서 XML 문서 읽기를 참조하세요.

스키마에 맞춰 유효성 검사

다음과 같이 XML 스키마로 시작합니다. 이 스키마는 XML의 데이터 형식과 필요한 특성을 정의합니다.

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  attributeFormDefault="unqualified"
  elementFormDefault="qualified"
  targetNamespace="http://www.contoso.com/books">
  <xs:element name="books">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="book">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="title" type="xs:string" />
              <xs:element name="price" type="xs:decimal" />
            </xs:sequence>
            <xs:attribute name="genre" type="xs:string" use="required" />
            <xs:attribute name="ISBN" type="xs:string" use="required" />
            <xs:attribute name="publicationdate" type="xs:date" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

스키마를 사용하여 개체를 XmlReader 만든 다음 해당 개체를 DOM에 로드합니다. 코드가 스키마 규칙을 위반하는 방식으로 XML 파일을 수정하려고 할 때 실행되는 이벤트 처리기를 만듭니다.

이러한 코드 블록은 이 모든 작업을 수행하는 도우미 메서드를 보여 줍니다.

//************************************************************************************
//
//  Helper method that generates an XML string.
//
//************************************************************************************
private string generateXMLString()
{
    string xml = "<?xml version=\"1.0\"?> \n" +
        "<books xmlns=\"http://www.contoso.com/books\"> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861001-57-8\" publicationdate=\"1823-01-28\"> \n" +
        "    <title>Pride And Prejudice</title> \n" +
        "    <price>24.95</price> \n" +
        "  </book> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861002-30-1\" publicationdate=\"1985-01-01\"> \n" +
        "    <title>The Handmaid's Tale</title> \n" +
        "    <price>29.95</price> \n" +
        "  </book> \n" +
        "  <book genre=\"novel\" ISBN=\"1-861001-45-3\" publicationdate=\"1811-01-01\"> \n" +
        "    <title>Sense and Sensibility</title> \n" +
        "    <price>19.95</price> \n" +
        "  </book> \n" +
        "</books>";
    return xml;
}

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************
public XmlDocument LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader reader = null;
    XmlReaderSettings settings = new XmlReaderSettings();
    // Helper method to retrieve schema.
    XmlSchema schema = getSchema(generateSchema);

    settings.Schemas.Add(schema);
    settings.ValidationEventHandler += ValidationCallback;
    settings.ValidationFlags =
        settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationType = ValidationType.Schema;
    if (!generateXML)
    {
        try
        {
            reader = XmlReader.Create("booksData.xml", settings);
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine(
                $"XML file not found so generating: {ex.Message}");
            generateXML = true;
        }
    }

    if (generateXML)
    {
        string xml = generateXMLString();
        StringReader stringReader = new StringReader(xml);

        reader = XmlReader.Create(stringReader, settings);
    }

    XmlDocument doc = new XmlDocument();

    doc.PreserveWhitespace = true;
    doc.Load(reader);
    reader.Close();

    return doc;
}

//************************************************************************************
//
//  Helper method that generates an XML Schema.
//
//************************************************************************************
private string generateXMLSchema()
{
    string xmlSchema =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
        "<xs:schema attributeFormDefault=\"unqualified\" " +
        "elementFormDefault=\"qualified\" targetNamespace=\"http://www.contoso.com/books\" " +
        "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"> " +
        "<xs:element name=\"books\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element maxOccurs=\"unbounded\" name=\"book\"> " +
        "<xs:complexType> " +
        "<xs:sequence> " +
        "<xs:element name=\"title\" type=\"xs:string\" /> " +
        "<xs:element name=\"price\" type=\"xs:decimal\" /> " +
        "</xs:sequence> " +
        "<xs:attribute name=\"genre\" type=\"xs:string\" use=\"required\" /> " +
        "<xs:attribute name=\"publicationdate\" type=\"xs:date\" use=\"required\" /> " +
        "<xs:attribute name=\"ISBN\" type=\"xs:string\" use=\"required\" /> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:sequence> " +
        "</xs:complexType> " +
        "</xs:element> " +
        "</xs:schema> ";
    return xmlSchema;
}

//************************************************************************************
//
//  Helper method that gets a schema
//
//************************************************************************************
private XmlSchema getSchema(bool generateSchema)
{
    XmlSchemaSet xs = new XmlSchemaSet();
    XmlSchema schema = null;

    if (!generateSchema)
    {
        try
        {
            schema = xs.Add("http://www.contoso.com/books", "booksData.xsd");
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine(
                $"XSD file not found so generating: {ex.Message}");
            generateSchema = true;
        }
    }

    if (generateSchema)
    {
        string xmlSchemaString = generateXMLSchema();
        StringReader stringReader = new StringReader(xmlSchemaString);
        XmlReader reader = XmlReader.Create(stringReader);

        schema = xs.Add("http://www.contoso.com/books", reader);
    }

    return schema;
}

//************************************************************************************
//
//  Helper method to validate the XML against the schema.
//
//************************************************************************************
private void validateXML(bool generateSchema, XmlDocument doc)
{
    if (doc.Schemas.Count == 0)
    {
        // Helper method to retrieve schema.
        XmlSchema schema = getSchema(generateSchema);
        doc.Schemas.Add(schema);
    }

    // Use a callback to validate the XML node against the schema.
    doc.Validate(ValidationCallback);
}

//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************
void ValidationCallback(object sender,
    System.Xml.Schema.ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {
        Console.WriteLine
            ("The following validation warning occurred: " + e.Message);
    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        Console.WriteLine
            ("The following critical validation errors occurred: " + e.Message);
    }
}
'************************************************************************************
'
'  Associate the schema with XML. Then, load the XML and validate it against
'  the schema.
'
'************************************************************************************
Public Function LoadDocumentWithSchemaValidation(ByVal generateXML As Boolean, ByVal generateSchema As Boolean) As XmlDocument
    Dim reader As XmlReader
    Dim settings As XmlReaderSettings = New XmlReaderSettings
    ' Helper method to retrieve schema.
    Dim schema As XmlSchema = getSchema(generateSchema)
    If (schema Is Nothing) Then
        Return Nothing
    End If
    settings.Schemas.Add(schema)
    AddHandler settings.ValidationEventHandler, AddressOf settings_ValidationEventHandler
    settings.ValidationFlags = (settings.ValidationFlags Or XmlSchemaValidationFlags.ReportValidationWarnings)
    settings.ValidationType = ValidationType.Schema
    Try
        reader = XmlReader.Create("booksData.xml", settings)
    Catch ex As System.IO.FileNotFoundException
        If generateXML Then
            Dim xml As String = generateXMLString()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xml)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            reader = XmlReader.Create(stream, settings)
        Else
            Return Nothing
        End If
    End Try
    Dim doc As XmlDocument = New XmlDocument
    doc.PreserveWhitespace = True
    doc.Load(reader)
    reader.Close()
    Return doc
End Function

'************************************************************************************
'
'  Helper method that generates an XML Schema.
'
'************************************************************************************
Private Function generateXMLSchema() As String

    Dim generatedXmlSchema As String = "<?xml version=""1.0"" encoding=""utf-8""?> " & _
            "<xs:schema attributeFormDefault=""unqualified"" " & _
            "elementFormDefault=""qualified"" targetNamespace=""http://www.contoso.com/books"" " & _
            "xmlns:xs=""http://www.w3.org/2001/XMLSchema""> " & _
            "<xs:element name=""books""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element maxOccurs=""unbounded"" name=""book""> " & _
            "<xs:complexType> " & _
            "<xs:sequence> " & _
            "<xs:element name=""title"" type=""xs:string"" /> " & _
            "<xs:element name=""price"" type=""xs:decimal"" /> " & _
            "</xs:sequence> " & _
            "<xs:attribute name=""genre"" type=""xs:string"" use=""required"" /> " & _
            "<xs:attribute name=""publicationdate"" type=""xs:date"" use=""required"" /> " & _
            "<xs:attribute name=""ISBN"" type=""xs:string"" use=""required"" /> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:sequence> " & _
            "</xs:complexType> " & _
            "</xs:element> " & _
            "</xs:schema> "


    Return generatedXmlSchema

End Function

'************************************************************************************
'
'  Helper method that gets a schema
'
'************************************************************************************
Private Function getSchema(ByVal generateSchema As Boolean) As XmlSchema
    Dim xs As XmlSchemaSet = New XmlSchemaSet
    Dim schema As XmlSchema
    Try
        schema = xs.Add("http://www.contoso.com/books", "booksData.xsd")
    Catch ex As System.IO.FileNotFoundException
        If generateSchema Then
            Dim xmlSchemaString As String = generateXMLSchema()
            Dim byteArray() As Byte = Encoding.UTF8.GetBytes(xmlSchemaString)
            Dim stream As MemoryStream = New MemoryStream(byteArray)
            Dim reader As XmlReader = XmlReader.Create(stream)
            schema = xs.Add("http://www.contoso.com/books", reader)
        Else
            Return Nothing
        End If
    End Try
    Return schema
End Function

'************************************************************************************
'
'  Helper method to validate the XML against the schema.
'
'************************************************************************************
Private Sub validateXML(ByVal generateSchema As Boolean, ByVal doc As XmlDocument)
    If (doc.Schemas.Count = 0) Then
        ' Helper method to retrieve schema.
        Dim schema As XmlSchema = getSchema(generateSchema)
        doc.Schemas.Add(schema)
    End If
    ' Use an event handler to validate the XML node against the schema.
    doc.Validate(AddressOf settings_ValidationEventHandler)
End Sub

'************************************************************************************
'
'  Event handler that is raised when XML doesn't validate against the schema.
'
'************************************************************************************
Private Sub settings_ValidationEventHandler(ByVal sender As Object, ByVal e As System.Xml.Schema.ValidationEventArgs)
    If (e.Severity = XmlSeverityType.Warning) Then
        System.Windows.Forms.MessageBox.Show(("The following validation warning occurred: " & e.Message))
    ElseIf (e.Severity = XmlSeverityType.Error) Then
        System.Windows.Forms.MessageBox.Show(("The following critical validation errors occurred: " & e.Message))
        Dim objectType As Type = sender.GetType
    End If
End Sub

자세한 내용은 DOM에서 XML 문서의 유효성 검사를 참조하세요.

속성을 사용하여 XML 문서를 탐색할 수 있습니다. 그러나 이러한 용어를 사용하기 전에 몇 가지 용어를 빠르게 검토해 보겠습니다. 문서는 노드로 구성됩니다. 각 노드에는 바로 위에 단일 부모 노드가 있습니다. 상위 노드가 없는 유일한 노드는 최상위 노드이므로 문서 루트입니다. 대부분의 노드에는 바로 아래에 있는 자식 노드가 있을 수 있습니다. 동일한 수준에 있는 노드는 형제입니다.

다음 예제에서는 루트 노드를 가져오고, 루트 노드의 첫 번째 자식 노드로 이동하고, 자식 노드에 액세스하고, 부모 노드로 다시 이동한 다음, 형제 노드를 탐색하는 방법을 보여 줍니다.

루트 노드 시작

이 예제에서는 루트 노드를 가져오고 해당 노드를 사용하여 문서의 내용을 콘솔에 출력합니다.

using System;
using System.IO;
using System.Xml;

public class Sample
{
  public static void Main()
  {
    //Create the XmlDocument.
    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<?xml version='1.0' ?>" +
                "<book genre='novel' ISBN='1-861001-57-5'>" +
                "<title>Pride And Prejudice</title>" +
                "</book>");

    //Display the document element.
    Console.WriteLine(doc.DocumentElement.OuterXml);
 }
}
Option Strict On
Option Explicit On
Imports System.Xml

Public Class ElementSample
    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.LoadXml("<?xml version='1.0' ?>" &
                    "<book genre='novel' ISBN='1-861001-57-5'>" &
                    "<title>Pride And Prejudice</title>" &
                    "</book>")

        'Display the document element.
        Console.WriteLine(doc.DocumentElement.OuterXml)
    End Sub
End Class

자식 노드 가져오기

이 예제에서는 루트 노드의 첫 번째 자식 노드로 이동한 다음 해당 노드의 자식 노드(있는 경우)를 반복합니다.

using System;
using System.Xml;

public class Sample2
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "<price>19.95</price>" +
                    "</book>");

        XmlNode root = doc.FirstChild;

        //Display the contents of the child nodes.
        if (root.HasChildNodes)
        {
            for (int i = 0; i < root.ChildNodes.Count; i++)
            {
                Console.WriteLine(root.ChildNodes[i].InnerText);
            }
        }
    }
}
Option Strict
Option Explicit

Imports System.IO
Imports System.Xml

Public Class Sample

    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" & _
                    "<title>Pride And Prejudice</title>" & _
                    "<price>19.95</price>" & _
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        'Display the contents of the child nodes.
        If root.HasChildNodes Then
            Dim i As Integer
            For i = 0 To root.ChildNodes.Count - 1
                Console.WriteLine(root.ChildNodes(i).InnerText)
            Next i
        End If
    End Sub
End Class

부모 노드로 돌아가기

ParentNode 속성을 사용합니다.

마지막 자식 노드를 참조하세요

이 예제에서는 책 가격을 콘솔에 씁니다. 가격 노드는 책 노드의 마지막 하위 노드입니다.

using System;
using System.Xml;

public class Sample3
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<book ISBN='1-861001-57-5'>" +
                    "<title>Pride And Prejudice</title>" +
                    "<price>19.95</price>" +
                    "</book>");

        XmlNode root = doc.FirstChild;

        Console.WriteLine("Display the price element...");
        Console.WriteLine(root.LastChild.OuterXml);
    }
}
Option Explicit On
Option Strict On
Imports System.Xml

Public Class LastChildSample
    Public Shared Sub Main()

        Dim doc As New XmlDocument()
        doc.LoadXml("<book ISBN='1-861001-57-5'>" &
                    "<title>Pride And Prejudice</title>" &
                    "<price>19.95</price>" &
                    "</book>")

        Dim root As XmlNode = doc.FirstChild

        Console.WriteLine("Display the price element...")
        Console.WriteLine(root.LastChild.OuterXml)
    End Sub
End Class

형제 간에 앞으로 이동

다음은 책에서 책으로 이동하는 예제입니다. 책 노드는 서로 형제입니다.

using System;
using System.Xml;

public class Sample4
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("books.xml");

        XmlNode currNode = doc.DocumentElement.FirstChild;
        Console.WriteLine("First book...");
        Console.WriteLine(currNode.OuterXml);

        XmlNode nextNode = currNode.NextSibling;
        Console.WriteLine("\r\nSecond book...");
        Console.WriteLine(nextNode.OuterXml);
    }
}
Imports System.Xml

Public Class NextSiblingSample
    Public Shared Sub Main()

        Dim doc As XmlDocument = New XmlDocument()
        doc.Load("books.xml")

        Dim currNode As XmlNode = doc.DocumentElement.FirstChild
        Console.WriteLine("First book...")
        Console.WriteLine(currNode.OuterXml)

        Dim nextNode As XmlNode = currNode.NextSibling
        Console.WriteLine(ControlChars.Lf + "Second book...")
        Console.WriteLine(nextNode.OuterXml)

    End Sub
End Class

형제 간에 뒤로 이동

이 예제는 책에서 책으로 거꾸로 이동합니다.

using System;
using System.Xml;

public class Sample {

  public static void Main() {

      XmlDocument doc = new XmlDocument();
      doc.Load("books.xml");

      XmlNode lastNode = doc.DocumentElement.LastChild;
      Console.WriteLine("Last book...");
      Console.WriteLine(lastNode.OuterXml);

      XmlNode prevNode = lastNode.PreviousSibling;
      Console.WriteLine("\r\nPrevious book...");
      Console.WriteLine(prevNode.OuterXml);
  }
}
Imports System.Xml

Public Class Sample5
    Public Shared Sub Main()
        Dim doc As XmlDocument = New XmlDocument()
        doc.Load("books.xml")

        Dim lastNode As XmlNode = doc.DocumentElement.LastChild
        Console.WriteLine("Last book...")
        Console.WriteLine(lastNode.OuterXml)

        Dim prevNode As XmlNode = lastNode.PreviousSibling
        Console.WriteLine(ControlChars.Lf + "Previous book...")
        Console.WriteLine(prevNode.OuterXml)
    End Sub
End Class

노드 찾기

하나 이상의 데이터 노드를 찾는 가장 인기 있는 방법은 XPath 쿼리 문자열을 사용하는 것이지만, 필요하지 않은 메서드도 있습니다.

단일 노드 가져오기

다음은 ISBN 번호를 사용하여 책을 찾는 예제입니다.

public XmlNode GetBook(string uniqueAttribute, XmlDocument doc)
{
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books");
    string xPathString = "//bk:books/bk:book[@ISBN='" + uniqueAttribute + "']";
    XmlNode xmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr);
   return xmlNode;
}
Public Function GetBook(ByVal uniqueAttribute As String, ByVal doc As XmlDocument) As XmlNode
    Dim nsmgr As XmlNamespaceManager = New XmlNamespaceManager(doc.NameTable)
    nsmgr.AddNamespace("bk", "http://www.contoso.com/books")
    Dim xPathString As String = ("//bk:books/bk:book[@ISBN='" _
                & (uniqueAttribute & "']"))
    Dim xmlNode As XmlNode = doc.DocumentElement.SelectSingleNode(xPathString, nsmgr)
    Return xmlNode
End Function

이 예제에서 사용되는 문자열은 Xpath 쿼리입니다. XPath 예제에서 더 많은 예제를 찾을 수 있습니다.

GetElementById를 사용하여 노드를 검색할 수도 있습니다. 이 방법을 사용하려면 XML 파일의 문서 형식 정의 선언에서 ID를 정의해야 합니다.

노드를 얻은 후, 속성 값이나 자식 노드의 값을 가져옵니다. 이 예제에서는 책 노드를 사용하여 이 작업을 수행합니다.

public void GetBookInformation(ref string title, ref string ISBN, ref string publicationDate,
    ref string price, ref string genre, XmlNode book)
{
    XmlElement bookElement = (XmlElement)book;

    // Get the attributes of a book.
    XmlAttribute attr = bookElement.GetAttributeNode("ISBN");
    ISBN = attr.InnerXml;

    attr = bookElement.GetAttributeNode("genre");
    genre = attr.InnerXml;

    attr = bookElement.GetAttributeNode("publicationdate");
    publicationDate = attr.InnerXml;

    // Get the values of child elements of a book.
    title = bookElement["title"].InnerText;
    price = bookElement["price"].InnerText;
}
Public Sub GetBookInformation(ByRef title As String, ByRef ISBN As String, ByRef publicationDate As String, ByRef price As String, ByRef genre As String, ByVal book As XmlNode)
    Dim bookElement As XmlElement = CType(book, XmlElement)
    ' Get the attributes of a book.
    Dim attr As XmlAttribute = bookElement.GetAttributeNode("ISBN")
    ISBN = attr.InnerXml
    attr = bookElement.GetAttributeNode("genre")
    genre = attr.InnerXml
    attr = bookElement.GetAttributeNode("publicationdate")
    publicationDate = attr.InnerXml
    ' Get the values of child elements of a book.
    title = bookElement("title").InnerText
    price = bookElement("price").InnerText
End Sub

노드 컬렉션 가져오기

다음은 저자의 성이 오스틴인 모든 책을 선택한 다음 해당 책의 가격을 변경하는 예제입니다.

using System;
using System.Xml;

public class Sample6
{
    public static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("booksort.xml");

        XmlNodeList nodeList;
        XmlNode root = doc.DocumentElement;

        nodeList = root.SelectNodes("descendant::book[author/last-name='Austen']");

        //Change the price on the books.
        foreach (XmlNode book in nodeList)
        {
            book.LastChild.InnerText = "15.95";
        }

        Console.WriteLine("Display the modified XML document....");
        doc.Save(Console.Out);
    }
}
Imports System.IO
Imports System.Xml

public class Sample

  public shared sub Main()

    'Create the XmlDocument.
    Dim doc as XmlDocument = new XmlDocument()
    doc.Load("booksort.xml")

    Dim book as XmlNode
    Dim nodeList as XmlNodeList
    Dim root as XmlNode = doc.DocumentElement

    nodeList=root.SelectNodes("descendant::book[author/last-name='Austen']")

    'Change the price on the books.
    for each book in nodeList
      book.LastChild.InnerText="15.95"
    next

    Console.WriteLine("Display the modified XML document....")
    doc.Save(Console.Out)

  end sub
end class

노드의 이름을 사용하여 노드 컬렉션을 가져올 수도 있습니다. 예를 들어 이 예제에서는 모든 책 제목의 컬렉션을 가져옵니다.

using System;
using System.Xml;

public class Sample1
{
    public static void Main()
    {
        //Create the XmlDocument.
        XmlDocument doc = new XmlDocument();
        doc.Load("books.xml");

        //Display all the book titles.
        XmlNodeList elemList = doc.GetElementsByTagName("title");
        for (int i = 0; i < elemList.Count; i++)
        {
            Console.WriteLine(elemList[i].InnerXml);
        }
    }
}
Option Explicit On
Option Strict On
Imports System.Xml

Public Class TagSample

    Public Shared Sub Main()
        'Create the XmlDocument.
        Dim doc As New XmlDocument()
        doc.Load("books.xml")

        'Display all the book titles.
        Dim elemList As XmlNodeList = doc.GetElementsByTagName("title")
        Dim i As Integer
        For i = 0 To elemList.Count - 1
            Console.WriteLine(elemList(i).InnerXml)
        Next i
    End Sub
End Class

자세한 내용은 XPath 탐색을 사용하여 노드 선택을 참조하세요.

노드 편집

이 예제에서는 책 노드 및 해당 특성을 편집합니다.

public void editBook(string title, string ISBN, string publicationDate,
    string genre, string price, XmlNode book, bool validateNode, bool generateSchema)
{

    XmlElement bookElement = (XmlElement)book;

    // Get the attributes of a book.
    bookElement.SetAttribute("ISBN", ISBN);
    bookElement.SetAttribute("genre", genre);
    bookElement.SetAttribute("publicationdate", publicationDate);

    // Get the values of child elements of a book.
    bookElement["title"].InnerText = title;
    bookElement["price"].InnerText = price;

    if (validateNode)
    {
        validateXML(generateSchema, bookElement.OwnerDocument);
    }
}
Public Sub editBook(ByVal title As String, ByVal ISBN As String,
                    ByVal publicationDate As String, ByVal genre As String,
                    ByVal price As String, ByVal book As XmlNode, ByVal validateNode As Boolean,
                    ByVal generateSchema As Boolean)

    Dim bookElement As XmlElement = CType(book, XmlElement)

    ' Get the attributes of a book.
    bookElement.SetAttribute("ISBN", ISBN)
    bookElement.SetAttribute("genre", genre)
    bookElement.SetAttribute("publicationdate", publicationDate)

    ' Get the values of child elements of a book.
    bookElement("title").InnerText = title
    bookElement("price").InnerText = price
    If validateNode Then
        validateXML(generateSchema, bookElement.OwnerDocument)
    End If

End Sub

자세한 내용은 XML 문서의 노드, 콘텐츠 및 값 수정을 참조하세요.

노드 추가

노드를 추가하려면 CreateElement 메서드 또는 CreateNode 메서드를 사용하십시오.

책과 같은 데이터 노드를 추가하려면 이 메서드를 CreateElement 사용합니다.

주석, 공백 노드 또는 CDATA 노드와 같은 다른 유형의 노드의 경우 이 메서드를 CreateNode 사용합니다.

다음은 책 노드를 만들고 해당 노드에 특성을 추가한 다음 해당 노드를 문서에 추가하는 예제입니다.

public XmlElement AddNewBook(string genre, string ISBN, string misc,
    string title, string price, XmlDocument doc)
{
    // Create a new book element.
    XmlElement bookElement = doc.CreateElement("book", "http://www.contoso.com/books");

    // Create attributes for book and append them to the book element.
    XmlAttribute attribute = doc.CreateAttribute("genre");
    attribute.Value = genre;
    bookElement.Attributes.Append(attribute);

    attribute = doc.CreateAttribute("ISBN");
    attribute.Value = ISBN;
    bookElement.Attributes.Append(attribute);

    attribute = doc.CreateAttribute("publicationdate");
    attribute.Value = misc;
    bookElement.Attributes.Append(attribute);

    // Create and append a child element for the title of the book.
    XmlElement titleElement = doc.CreateElement("title");
    titleElement.InnerText = title;
    bookElement.AppendChild(titleElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml =
        bookElement.InnerXml.Replace(titleElement.OuterXml,
        "\n    " + titleElement.OuterXml + " \n    ");

    // Create and append a child element for the price of the book.
    XmlElement priceElement = doc.CreateElement("price");
    priceElement.InnerText= price;
    bookElement.AppendChild(priceElement);

    // Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml =
        bookElement.InnerXml.Replace(priceElement.OuterXml, priceElement.OuterXml + "   \n  ");

    return bookElement;
}
Public Function AddNewBook(ByVal genre As String, ByVal ISBN As String, ByVal misc As String, ByVal title As String, ByVal price As String, ByVal doc As XmlDocument) As XmlElement
    ' Create a new book element.
    Dim bookElement As XmlElement = doc.CreateElement("book", "http://www.contoso.com/books")

    ' Create attributes for book and append them to the book element.
    Dim attribute As XmlAttribute = doc.CreateAttribute("genre")
    attribute.Value = genre
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("ISBN")
    attribute.Value = ISBN
    bookElement.Attributes.Append(attribute)

    attribute = doc.CreateAttribute("publicationdate")
    attribute.Value = misc
    bookElement.Attributes.Append(attribute)

    ' Create and append a child element for the title of the book.
    Dim titleElement As XmlElement = doc.CreateElement("title")
    titleElement.InnerText = title
    bookElement.AppendChild(titleElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(titleElement.OuterXml, _
                           "\n   " & titleElement.OuterXml & " " & ControlChars.NewLine + "    ")
    ' Create and append a child element for the price of the book.
    Dim priceElement As XmlElement = doc.CreateElement("price")
    priceElement.InnerText = price
    bookElement.AppendChild(priceElement)

    ' Introduce a newline character so that XML is nicely formatted.
    bookElement.InnerXml = bookElement.InnerXml.Replace(priceElement.OuterXml,
                                                        (priceElement.OuterXml & "   " & ControlChars.NewLine & "  "))
    Return bookElement
End Function

자세한 내용은 XML 문서에 노드 삽입을 참조하세요.

노드 제거

노드를 제거하려면 메서드를 RemoveChild 사용합니다.

다음은 문서에서 책과 책 노드 바로 앞에 나타나는 공백을 제거하는 예제입니다.

public void deleteBook(XmlNode book)
{
    XmlNode prevNode = book.PreviousSibling;

    book.OwnerDocument.DocumentElement.RemoveChild(book);

    if (prevNode.NodeType == XmlNodeType.Whitespace ||
        prevNode.NodeType == XmlNodeType.SignificantWhitespace)
    {
        prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode);
    }
}
Public Sub deleteBook(ByVal book As XmlNode)

    Dim prevNode As XmlNode = book.PreviousSibling
    book.OwnerDocument.DocumentElement.RemoveChild(book)

    If ((prevNode.NodeType = XmlNodeType.Whitespace) _
                OrElse (prevNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
        prevNode.OwnerDocument.DocumentElement.RemoveChild(prevNode)

    End If
End Sub

자세한 내용은 XML 문서에서 노드, 콘텐츠 및 값 제거를 참조하세요.

노드 위치 지정

사용자는 InsertBeforeInsertAfter 메서드를 사용하여 문서에서 노드가 나타날 위치를 선택할 수 있습니다.

이 예제에서는 두 가지 도우미 메서드를 보여 줍니다. 그 중 하나는 목록에서 노드를 더 높게 이동합니다. 다른 하나는 노드를 더 낮게 이동합니다.

이러한 방법은 사용자가 책 목록에서 책을 위아래로 이동할 수 있도록 하는 애플리케이션에서 사용할 수 있습니다. 사용자가 책을 선택하고 위쪽 또는 아래쪽 단추를 누르면 코드에서 이와 같은 메서드를 호출하여 다른 책 노드 앞이나 뒤의 해당 책 노드를 배치할 수 있습니다.

//************************************************************************************
//
//  Summary: Move elements up in the XML.
//
//
//************************************************************************************

public void MoveElementUp(XmlNode book)
{
    XmlNode previousNode = book.PreviousSibling;
    while (previousNode != null && (previousNode.NodeType != XmlNodeType.Element))
    {
        previousNode = previousNode.PreviousSibling;
    }
    if (previousNode != null)
    {
        XmlNode newLineNode = book.NextSibling;
        book.OwnerDocument.DocumentElement.RemoveChild(book);
        if (newLineNode.NodeType == XmlNodeType.Whitespace |
            newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
        {
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
        }
        InsertBookElement((XmlElement)book, Constants.positionAbove,
            previousNode, false, false);
    }
}

//************************************************************************************
//
//  Summary: Move elements down in the XML.
//
//
//************************************************************************************
public void MoveElementDown(XmlNode book)
{
    // Walk backwards until we find an element - ignore text nodes
    XmlNode NextNode = book.NextSibling;
    while (NextNode != null && (NextNode.NodeType != XmlNodeType.Element))
    {
        NextNode = NextNode.NextSibling;
    }
    if (NextNode != null)
    {
        XmlNode newLineNode = book.PreviousSibling;
        book.OwnerDocument.DocumentElement.RemoveChild(book);
        if (newLineNode.NodeType == XmlNodeType.Whitespace |
            newLineNode.NodeType == XmlNodeType.SignificantWhitespace)
        {
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode);
        }

        InsertBookElement((XmlElement)book, Constants.positionBelow,
            NextNode, false, false);
    }
}
'************************************************************************************
'
'  Summary: Move elements up in the XML.
'
'
'************************************************************************************
Public Sub MoveElementUp(ByVal book As XmlNode)
    Dim previousNode As XmlNode = book.PreviousSibling

    While ((Not (previousNode) Is Nothing) _
                AndAlso (previousNode.NodeType <> XmlNodeType.Element))
        previousNode = previousNode.PreviousSibling

    End While
    If (Not (previousNode) Is Nothing) Then
        Dim newLineNode As XmlNode = book.NextSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionAbove,
                          previousNode, False, False)
    End If
End Sub

'************************************************************************************
'
'  Summary: Move elements down in the XML.
'
'
'************************************************************************************
Public Sub MoveElementDown(ByVal book As XmlNode)
    ' Walk backwards until we find an element - ignore text nodes
    Dim NextNode As XmlNode = book.NextSibling

    While ((Not (NextNode) Is Nothing) _
                AndAlso (NextNode.NodeType <> XmlNodeType.Element))
        NextNode = NextNode.NextSibling

    End While

    If (Not (NextNode) Is Nothing) Then
        Dim newLineNode As XmlNode = book.PreviousSibling
        book.OwnerDocument.DocumentElement.RemoveChild(book)

        If ((newLineNode.NodeType = XmlNodeType.Whitespace) _
                    Or (newLineNode.NodeType = XmlNodeType.SignificantWhitespace)) Then
            newLineNode.OwnerDocument.DocumentElement.RemoveChild(newLineNode)
        End If

        InsertBookElement(CType(book, XmlElement), Constants.positionBelow,
                          NextNode, False, False)
    End If
End Sub

생성자

Name Description
XmlDocument()

XmlDocument 클래스의 새 인스턴스를 초기화합니다.

XmlDocument(XmlImplementation)

지정된 클래스를 사용하여 클래스의 XmlDocument 새 인스턴스를 초기화합니다 XmlImplementation.

XmlDocument(XmlNameTable)

지정된 클래스를 사용하여 클래스의 XmlDocument 새 인스턴스를 초기화합니다 XmlNameTable.

속성

Name Description
Attributes

XmlAttributeCollection 이 노드의 특성을 포함하는 값을 가져옵니다.

(다음에서 상속됨 XmlNode)
BaseURI

현재 노드의 기본 URI를 가져옵니다.

ChildNodes

노드의 모든 자식 노드를 가져옵니다.

(다음에서 상속됨 XmlNode)
DocumentElement

문서의 루트 XmlElement 를 가져옵니다.

DocumentType

DOCTYPE 선언을 포함하는 노드를 가져옵니다.

FirstChild

노드의 첫 번째 자식 값을 가져옵니다.

(다음에서 상속됨 XmlNode)
HasChildNodes

이 노드에 자식 노드가 있는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 XmlNode)
Implementation

XmlImplementation 현재 문서의 개체를 가져옵니다.

InnerText

모든 경우에 throw InvalidOperationException 합니다.

InnerText

노드 및 모든 자식 노드의 연결된 값을 가져오거나 설정합니다.

(다음에서 상속됨 XmlNode)
InnerXml

현재 노드의 자식을 나타내는 태그를 가져오거나 설정합니다.

IsReadOnly

현재 노드가 읽기 전용인지 여부를 나타내는 값을 가져옵니다.

Item[String, String]

지정 LocalName 한 자식 요소와 NamespaceURI.를 사용하여 첫 번째 자식 요소를 가져옵니다.

(다음에서 상속됨 XmlNode)
Item[String]

지정된 Name자식 요소가 있는 첫 번째 자식 요소를 가져옵니다.

(다음에서 상속됨 XmlNode)
LastChild

노드의 마지막 자식 값을 가져옵니다.

(다음에서 상속됨 XmlNode)
LocalName

노드의 로컬 이름을 가져옵니다.

Name

노드의 정규화된 이름을 가져옵니다.

NamespaceURI

이 노드의 네임스페이스 URI를 가져옵니다.

(다음에서 상속됨 XmlNode)
NameTable

XmlNameTable 이 구현과 연결된 값을 가져옵니다.

NextSibling

이 노드 바로 다음의 노드를 가져옵니다.

(다음에서 상속됨 XmlNode)
NodeType

현재 노드의 형식을 가져옵니다.

OuterXml

이 노드와 모든 자식 노드를 포함하는 태그를 가져옵니다.

(다음에서 상속됨 XmlNode)
OwnerDocument

현재 노드가 XmlDocument 속한 노드를 가져옵니다.

ParentNode

이 노드의 부모 노드를 가져옵니다(부모가 있을 수 있는 노드의 경우).

ParentNode

이 노드의 부모(부모가 있을 수 있는 노드의 경우)를 가져옵니다.

(다음에서 상속됨 XmlNode)
Prefix

이 노드의 네임스페이스 접두사를 가져오거나 설정합니다.

(다음에서 상속됨 XmlNode)
PreserveWhitespace

요소 콘텐츠에서 공백을 유지할지 여부를 나타내는 값을 가져오거나 설정합니다.

PreviousSibling

이 노드 바로 앞에 있는 노드를 가져옵니다.

(다음에서 상속됨 XmlNode)
PreviousText

이 노드 바로 앞에 있는 텍스트 노드를 가져옵니다.

(다음에서 상속됨 XmlNode)
SchemaInfo

노드의 PSVI(Post-Schema-Validation-Infoset)를 반환합니다.

Schemas

XmlSchemaSet개체와 연결된 개체를 XmlDocument 가져오거나 설정합니다.

Value

노드의 값을 가져오거나 설정합니다.

(다음에서 상속됨 XmlNode)
XmlResolver

XmlResolver 외부 리소스를 확인하는 데 사용할 값을 설정합니다.

메서드

Name Description
AppendChild(XmlNode)

지정된 노드를 이 노드의 자식 노드 목록 끝에 추가합니다.

(다음에서 상속됨 XmlNode)
Clone()

이 노드의 복제본을 만듭니다.

(다음에서 상속됨 XmlNode)
CloneNode(Boolean)

이 노드의 복제본을 만듭니다.

CreateAttribute(String, String, String)

지정된 XmlAttributePrefix, LocalNameNamespaceURI.를 사용하여 만듭니다.

CreateAttribute(String, String)

XmlAttribute 지정된 정규화된 이름과 NamespaceURI.을 사용하여 만듭니다.

CreateAttribute(String)

지정된 XmlAttribute을 사용하여 Name 만듭니다.

CreateCDataSection(String)

XmlCDataSection 지정된 데이터가 포함된 데이터를 만듭니다.

CreateComment(String)

XmlComment 지정된 데이터가 포함된 데이터를 만듭니다.

CreateDefaultAttribute(String, String, String)

지정된 접두사, 로컬 이름 및 네임스페이스 URI를 사용하여 기본 특성을 만듭니다.

CreateDocumentFragment()

XmlDocumentFragment를 만듭니다.

CreateDocumentType(String, String, String, String)

XmlDocumentType 개체를 반환합니다.

CreateElement(String, String, String)

지정된 PrefixLocalNameNamespaceURI및 을 사용하여 요소를 만듭니다.

CreateElement(String, String)

XmlElement 정규화된 이름과 NamespaceURI.을 사용하여 만듭니다.

CreateElement(String)

지정된 이름을 가진 요소를 만듭니다.

CreateEntityReference(String)

지정된 이름을 사용하여 XmlEntityReference 만듭니다.

CreateNavigator()

이 문서를 탐색하기 위한 새 XPathNavigator 개체를 만듭니다.

CreateNavigator()

이 개체를 XPathNavigator 탐색하기 위한 개체를 만듭니다.

(다음에서 상속됨 XmlNode)
CreateNavigator(XmlNode)

XPathNavigator 지정된 위치에 있는 이 문서를 탐색하기 위한 개체를 XmlNode 만듭니다.

CreateNode(String, String, String)

XmlNode 지정된 노드 형식NameNamespaceURI을 사용하여 및 .를 만듭니다.

CreateNode(XmlNodeType, String, String, String)

지정된 XmlNode, XmlNodeTypePrefixName.를 사용하여 a NamespaceURI 를 만듭니다.

CreateNode(XmlNodeType, String, String)

지정된 XmlNodeXmlNodeType, NameNamespaceURI.를 사용하여 만듭니다.

CreateProcessingInstruction(String, String)

지정된 이름 및 데이터를 사용하여 XmlProcessingInstruction 만듭니다.

CreateSignificantWhitespace(String)

노드를 XmlSignificantWhitespace 만듭니다.

CreateTextNode(String)

지정된 텍스트를 사용하여 XmlText 만듭니다.

CreateWhitespace(String)

노드를 XmlWhitespace 만듭니다.

CreateXmlDeclaration(String, String, String)

지정된 값을 사용하여 XmlDeclaration 노드를 만듭니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 여부를 확인합니다.

(다음에서 상속됨 Object)
GetElementById(String)

지정된 ID를 XmlElement 가진 값을 가져옵니다.

GetElementsByTagName(String, String)

XmlNodeList 지정된 LocalName 요소와 일치하는 모든 하위 요소의 목록을 포함하는 반환합니다NamespaceURI.

GetElementsByTagName(String)

XmlNodeList 지정된 Name요소와 일치하는 모든 하위 요소의 목록을 포함하는 반환합니다.

GetEnumerator()

현재 노드의 자식 노드를 반복하는 열거자를 가져옵니다.

(다음에서 상속됨 XmlNode)
GetHashCode()

기본 해시 함수로 사용됩니다.

(다음에서 상속됨 Object)
GetNamespaceOfPrefix(String)

현재 노드의 범위에 있는 지정된 접두사에 대한 가장 가까운 xmlns 선언을 조회하고 선언에서 네임스페이스 URI를 반환합니다.

(다음에서 상속됨 XmlNode)
GetPrefixOfNamespace(String)

현재 노드의 범위에 있는 지정된 네임스페이스 URI에 대한 가장 가까운 xmlns 선언을 조회하고 해당 선언에 정의된 접두사를 반환합니다.

(다음에서 상속됨 XmlNode)
GetType()

현재 인스턴스의 Type 가져옵니다.

(다음에서 상속됨 Object)
ImportNode(XmlNode, Boolean)

다른 문서에서 현재 문서로 노드를 가져옵니다.

InsertAfter(XmlNode, XmlNode)

지정된 참조 노드 바로 뒤에 지정된 노드를 삽입합니다.

(다음에서 상속됨 XmlNode)
InsertBefore(XmlNode, XmlNode)

지정된 참조 노드 바로 앞에 지정된 노드를 삽입합니다.

(다음에서 상속됨 XmlNode)
Load(Stream)

지정된 스트림에서 XML 문서를 로드합니다.

Load(String)

지정된 URL에서 XML 문서를 로드합니다.

Load(TextReader)

지정된 에서 XML 문서를 로드합니다 TextReader.

Load(XmlReader)

지정된 에서 XML 문서를 로드합니다 XmlReader.

LoadXml(String)

지정된 문자열에서 XML 문서를 로드합니다.

MemberwiseClone()

현재 Object단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
Normalize()

이 XmlNode 아래 하위 트리의 전체 깊이에 있는 모든 XmlText 노드를 태그(즉, 태그, 주석, 처리 명령, CDATA 섹션 및 엔터티 참조)만 XmlText 노드를 구분하는 "일반" 형식으로 배치합니다. 즉, 인접한 XmlText 노드가 없습니다.

(다음에서 상속됨 XmlNode)
PrependChild(XmlNode)

지정된 노드를 이 노드에 대한 자식 노드 목록의 시작 부분에 추가합니다.

(다음에서 상속됨 XmlNode)
ReadNode(XmlReader)

XmlNode 정보를 기반으로 개체를 XmlReader만듭니다. 판독기는 노드 또는 특성에 위치해야 합니다.

RemoveAll()

현재 노드의 모든 자식 노드 및/또는 특성을 제거합니다.

(다음에서 상속됨 XmlNode)
RemoveChild(XmlNode)

지정된 자식 노드를 제거합니다.

(다음에서 상속됨 XmlNode)
ReplaceChild(XmlNode, XmlNode)

자식 노드를 노드 oldChild 로 바 newChild 꿉니다.

(다음에서 상속됨 XmlNode)
Save(Stream)

XML 문서를 지정된 스트림에 저장합니다.

Save(String)

XML 문서를 지정된 파일에 저장합니다. 지정된 파일이 있는 경우 이 메서드는 덮어씁니다.

Save(TextWriter)

XML 문서를 지정된 에 저장합니다 TextWriter.

Save(XmlWriter)

XML 문서를 지정된 에 저장합니다 XmlWriter.

SelectNodes(String, XmlNamespaceManager)

XPath 식과 일치하는 노드 목록을 선택합니다. XPath 식에 있는 모든 접두사는 제공 XmlNamespaceManager된 접두사를 사용하여 확인됩니다.

(다음에서 상속됨 XmlNode)
SelectNodes(String)

XPath 식과 일치하는 노드 목록을 선택합니다.

(다음에서 상속됨 XmlNode)
SelectSingleNode(String, XmlNamespaceManager)

XPath 식과 일치하는 첫 번째 XmlNode 항목을 선택합니다. XPath 식에 있는 모든 접두사는 제공 XmlNamespaceManager된 접두사를 사용하여 확인됩니다.

(다음에서 상속됨 XmlNode)
SelectSingleNode(String)

XPath 식과 일치하는 첫 번째 XmlNode 항목을 선택합니다.

(다음에서 상속됨 XmlNode)
Supports(String, String)

DOM 구현이 특정 기능을 구현하는지 테스트합니다.

(다음에서 상속됨 XmlNode)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)
Validate(ValidationEventHandler, XmlNode)

속성의 XmlNode XSD(XML 스키마 정의 언어) 스키마에 대해 지정된 개체의 유효성을 Schemas 검사합니다.

Validate(ValidationEventHandler)

속성에 XmlDocument 포함된 XSD(XML 스키마 정의 언어) 스키마에 대해 유효성을 Schemas 검사합니다.

WriteContentTo(XmlWriter)

노드의 XmlDocument 모든 자식을 지정된 자식에 저장합니다 XmlWriter.

WriteTo(XmlWriter)

노드를 XmlDocument 지정된 XmlWriter에 저장합니다.

이벤트

Name Description
NodeChanged

이 문서에 속한 노드가 변경되었을 때 Value 발생합니다.

NodeChanging

이 문서에 속한 노드가 변경될 때 Value 발생합니다.

NodeInserted

이 문서에 속한 노드가 다른 노드에 삽입될 때 발생합니다.

NodeInserting

이 문서에 속한 노드를 다른 노드에 삽입하려고 할 때 발생합니다.

NodeRemoved

이 문서에 속한 노드가 부모에서 제거될 때 발생합니다.

NodeRemoving

이 문서에 속한 노드를 문서에서 제거하려고 할 때 발생합니다.

명시적 인터페이스 구현

Name Description
ICloneable.Clone()

이 멤버에 대한 설명은 을 참조하세요 Clone().

(다음에서 상속됨 XmlNode)
IEnumerable.GetEnumerator()

이 멤버에 대한 설명은 을 참조하세요 GetEnumerator().

(다음에서 상속됨 XmlNode)

확장명 메서드

Name Description
AsParallel(IEnumerable)

쿼리의 병렬 처리를 사용하도록 설정합니다.

AsQueryable(IEnumerable)

IEnumerable IQueryable변환합니다.

Cast<TResult>(IEnumerable)

IEnumerable 요소를 지정된 형식으로 캐스팅합니다.

CreateNavigator(XmlDocument, XmlNode)

지정된 노드에 배치된 지정한 문서를 탐색하기 위한 XPath 탐색기 개체를 만듭니다.

CreateNavigator(XmlDocument)

지정된 문서를 탐색하기 위한 새 XPath 탐색기 개체를 만듭니다.

CreateNavigator(XmlNode)

지정된 노드를 탐색하기 위한 XPath 탐색기를 만듭니다.

OfType<TResult>(IEnumerable)

지정된 형식에 따라 IEnumerable 요소를 필터링합니다.

SelectNodes(XmlNode, String, XmlNamespaceManager)

지정된 XPath 식과 일치하는 노드 목록을 선택합니다. XPath 식에 있는 모든 접두사는 제공된 네임스페이스 관리자를 사용하여 확인됩니다.

SelectNodes(XmlNode, String)

지정된 XPath 식과 일치하는 노드 목록을 선택합니다.

SelectSingleNode(XmlNode, String, XmlNamespaceManager)

XPath 식과 일치하는 첫 번째 노드를 선택합니다. XPath 식에 있는 모든 접두사는 제공된 네임스페이스 관리자를 사용하여 확인됩니다.

SelectSingleNode(XmlNode, String)

XPath 식과 일치하는 첫 번째 노드를 선택합니다.

ToXPathNavigable(XmlNode)

탐색기를 IXPathNavigable 생성하는 데 사용되는 인스턴스를 만듭니다.

적용 대상

추가 정보