XmlDocument XmlDocument XmlDocument XmlDocument Class

정의

XML 문서를 나타냅니다.Represents an XML document. 이 클래스를 사용하여 문서에서 XML 로드, 유효성 검사, 편집, 추가 및 위치 지정을 수행할 수 있습니다.You can use this class to load, validate, edit, add, and position XML in a document.

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

설명

XmlDocument 클래스는 XML 문서의 메모리 내 표현입니다.The XmlDocument class is an in-memory representation of an XML document. W3C 구현 XML 문서 개체 모델 (DOM) Level 1 Core 및 DOM Level 2 Core.It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2.

DOM 의미 문서 개체 모델합니다.DOM stands for document object model. 자세한 정보를 참조 하세요 XML 문서 개체 모델 (DOM)합니다.To read more about it, see XML Document Object Model (DOM).

사용 하 여 XML DOM에 로드할 수 있습니다는 XmlDocument 클래스 및 다음 프로그래밍 방식으로 읽기, 수정 및 XML 문서에서 제거 합니다.You can load XML into the DOM by using the XmlDocument class, and then programmatically read, modify, and remove XML in the document.

들어 올릴 엽니다는 XmlDocument 클래스 및 구현 하는 방법을 참조 하십시오 합니다 참조 소스합니다.If you want to pry open the XmlDocument class and see how it's implemented, see the Reference Source.

작업Tasks

XML 문서 개체 모델에 로드Load XML into the document object model

몇 가지 온라인 설명서 컬렉션에 있는 다음과 같은 XML 문서를 사용 하 여 시작 합니다.Start with an XML document like this one that has a few books in a collection. 네임 스페이스, 데이터를 나타내는 요소 및 데이터를 설명 하는 특성을 포함 하 여 XML 문서에서 찾을 수 있는 기본 작업을 포함 합니다.It contains the basic things that you'd find in any XML document, including a namespace, elements that represent data, and attributes that describe the data.

<?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에이 데이터를 로드 합니다.Next, load this data into the DOM so that you can work with it in memory. 이 작업을 수행 하는 가장 인기 있는 방법은 아니지만 네트워크 또는 로컬 컴퓨터에 파일을 참조 하십시오입니다.The most popular way to do this is refer to a file on your local computer or on a network.

이 예제에서는 파일에서 XML을 로드 합니다.This example loads XML from a file. 파일이 없으면 바로 일부 XML을 생성 하 고이 로드 하 합니다.If the file doesn't exist, it just generates some XML and loads that.

XmlDocument ^doc = gcnew XmlDocument();
doc->PreserveWhitespace = true;
try
{doc->Load("booksData.xml");}
catch (System::IO::FileNotFoundException ^e1)
{
	// If no book is found, generate some XML.

	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>");
}
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

전체 샘플의 경우: XmlDocument 클래스 및 기타 관련된 형식을 사용 하 여 메모리에서 XML 조작Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

자세한 정보: DOM에 XML 문서 읽어오기Learn more: Reading an XML Document into the DOM

스키마에 대해 유효성 검사Validate it against a schema

이와 같은 XML 스키마를 사용 하 여 시작 합니다.Start with an XML schema like this one. 이 스키마는 XML 데이터 형식을 정의 하 고 필요한 특성을 합니다.This schema defines the data types in the XML and which attributes are required.

<?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 개체 로드 한 다음Create an XmlReader object by using your schema, and then load that object into the DOM. 코드는 스키마의 규칙을 위반 하는 방법으로 XML 파일을 수정 하려고 할 때 실행 하는 이벤트 처리기를 만듭니다.Create an event handler that executes when code attempts to modify your XML file in ways that violate the rules of the schema.

이러한 코드 블록을이 모든 작업을 수행 하는 도우미 메서드를 보여 줍니다.These blocks of code show helper methods that do all of this.

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************

XmlDocument ^XMLDOMProcessing::XMLHelperMethods::LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
	XmlReader ^reader;

	XmlReaderSettings ^settings = gcnew XmlReaderSettings();

	// Helper method to retrieve schema.
	XmlSchema ^schema = getSchema(generateSchema);
	
	if (schema == nullptr)
	{
		return nullptr;
	}

	settings->Schemas->Add(schema);
	settings->ValidationEventHandler +=
		gcnew System::Xml::Schema::ValidationEventHandler
		(this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);
	settings->ValidationFlags = settings->ValidationFlags | XmlSchemaValidationFlags::ReportValidationWarnings;
	settings->ValidationType = ValidationType::Schema;

	try
	{
		reader = XmlReader::Create("booksData.xml", settings);
	}
	catch (System::IO::FileNotFoundException ^e1)
	{
		if (generateXML)
		{
			String ^xml = generateXMLString();
			array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xml);
			MemoryStream ^stream = gcnew MemoryStream(byteArray);
			reader = XmlReader::Create(stream, settings);
		}
		else
		{
			return nullptr;
		}

	}

	XmlDocument ^doc = gcnew XmlDocument();
	doc->PreserveWhitespace = true;
	doc->Load(reader);
	reader->Close();

	return doc;
}

//************************************************************************************
//
//  Helper method that generates an XML Schema.
//
//************************************************************************************

String ^XMLDOMProcessing::XMLHelperMethods::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
//
//************************************************************************************

XmlSchema ^XMLDOMProcessing::XMLHelperMethods::getSchema(bool generateSchema)
{
	XmlSchemaSet ^xs = gcnew XmlSchemaSet();
	XmlSchema ^schema;
	try
	{
		schema = xs->Add("http://www.contoso.com/books", "booksData.xsd");
	}
	catch (System::IO::FileNotFoundException ^e1)
	{
		if (generateSchema)
		{
			String ^xmlSchemaString = generateXMLSchema();
			array<Byte> ^byteArray = Encoding::UTF8->GetBytes(xmlSchemaString);
			MemoryStream ^stream = gcnew MemoryStream(byteArray);
			XmlReader ^reader = XmlReader::Create(stream);
			schema = xs->Add("http://www.contoso.com/books", reader);
		}
		else
		{
			return nullptr;
		}

	}
	return schema;
}
//************************************************************************************
//
//  Helper method to validate the XML against the schema.
//
//************************************************************************************
bool XMLDOMProcessing::XMLHelperMethods::validateXML(bool generateSchema, XmlDocument ^doc)
{
	if (doc->Schemas->Count == 0)
	{
		// Helper method to retrieve schema.
		XmlSchema ^schema = getSchema(generateSchema);
		doc->Schemas->Add(schema);
	}

	ValidationEventHandler^ eventHandler = gcnew System::Xml::Schema::ValidationEventHandler
		(this, &XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler);

	// Use an event handler to validate the XML node against the schema.
	doc->Validate(eventHandler);

	if (_IsValid == false)
	{
		_IsValid = true;
		return false;
	}
	else
	{
		return true;
	}

}
//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************

void XMLDOMProcessing::XMLHelperMethods::OnValidationEventHandler(System::Object ^sender, System::Xml::Schema::ValidationEventArgs ^e)
{
	if (e->Severity == XmlSeverityType::Warning)
	{
		// do nothing.
	}
	else if (e->Severity == XmlSeverityType::Error)
	{
		// set some global variables.
		_IsValid = false;
		ValidationError = e->Message;
	}
}

//************************************************************************************
//
//  Associate the schema with XML. Then, load the XML and validate it against
//  the schema.
//
//************************************************************************************
public XmlDocument LoadDocumentWithSchemaValidation(bool generateXML, bool generateSchema)
{
    XmlReader reader;

    XmlReaderSettings settings = new XmlReaderSettings();

    // Helper method to retrieve schema.
    XmlSchema schema = getSchema(generateSchema);

    if (schema == null)
    {
        return null;
    }

    settings.Schemas.Add(schema);

    settings.ValidationEventHandler += settings_ValidationEventHandler;
    settings.ValidationFlags =
        settings.ValidationFlags | XmlSchemaValidationFlags.ReportValidationWarnings;
    settings.ValidationType = ValidationType.Schema;

    try
    {
        reader = XmlReader.Create("booksData.xml", settings);
    }
    catch (System.IO.FileNotFoundException)
    {
        if (generateXML)
        {
            string xml = generateXMLString();
            byte[] byteArray = Encoding.UTF8.GetBytes(xml);
            MemoryStream stream = new MemoryStream(byteArray);
            reader = XmlReader.Create(stream, settings);
        }
        else
        {
            return null;
        }

    }

    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;
    try
    {
        schema = xs.Add("http://www.contoso.com/books", "booksData.xsd");
    }
    catch (System.IO.FileNotFoundException)
    {
        if (generateSchema)
        {
            string xmlSchemaString = generateXMLSchema();
            byte[] byteArray = Encoding.UTF8.GetBytes(xmlSchemaString);
            MemoryStream stream = new MemoryStream(byteArray);
            XmlReader reader = XmlReader.Create(stream);
            schema = xs.Add("http://www.contoso.com/books", reader);
        }
        else
        {
            return null;
        }

    }
    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 an event handler to validate the XML node against the schema.
    doc.Validate(settings_ValidationEventHandler);

}

//************************************************************************************
//
//  Event handler that is raised when XML doesn't validate against the schema.
//
//************************************************************************************
void settings_ValidationEventHandler(object sender,
    System.Xml.Schema.ValidationEventArgs e)
{
    if (e.Severity == XmlSeverityType.Warning)
    {
        System.Windows.Forms.MessageBox.Show
            ("The following validation warning occurred: " + e.Message);
    }
    else if (e.Severity == XmlSeverityType.Error)
    {
        System.Windows.Forms.MessageBox.Show
            ("The following critical validation errors occurred: " + e.Message);
        Type objectType = sender.GetType();
    }

}
'************************************************************************************
'
'  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

전체 샘플의 경우: XmlDocument 클래스 및 기타 관련된 형식을 사용 하 여 메모리에서 XML 조작Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

자세한 정보: DOM에서의 XML 문서 유효성 검사Learn more: Validating an XML Document in the DOM

XML 문서를 탐색 하려면 속성을 사용할 수 있습니다.You can use properties to navigate around an XML document. 하지만 그 중 하나를 사용 하기 전에 신속 하 게 살펴보겠습니다 몇 가지 용어입니다.But before you use any of them, let's quickly review a few terms. 문서 노드의 구성 됩니다.Your document is composed of nodes. 각 노드에 단일 부모 바로 위의 노드.Each node has as single parent node directly above it. 부모 노드에 없는 유일한 노드이거나 문서 루트는 최상위 노드입니다.The only node that does not have a parent node is the document root, as it is the top-level node. 대부분의 노드 수 자식 노드인, 노드 바로 아래에 있습니다.Most nodes can have child nodes, which are nodes directly below them. 동일한 수준에 있는 노드가 형제합니다.Nodes that are at the same level are siblings.

다음 예제에서는 루트 노드를 가져올, 루트 노드의 첫 번째 자식 노드로 이동, 해당 자식 노드 중 하나를 액세스, 돌아갈 부모 노드를 이동한 다음 형제 노드에서 방법을 보여 줍니다.The following examples show you how to obtain the root node, jump to the first child node of the root node, access any of its child nodes, get back out to the parent node, and then navigate across sibling nodes.

루트 노드를 사용 하 여 시작Start with the root node

이 예제에서는 루트 노드를 가져오고 해당 노드를 사용 하 여 콘솔에 문서의 내용을 출력 하려면.This example gets the root node and then uses that node to output the contents of the document to the console.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew 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 );
}

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

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample
    
    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 'Main
End Class 'Sample

자식 노드 가져오기Get child nodes

이 예제에서는 루트 노드의 첫 번째 자식 노드로 이동 하 고 있는 경우 해당 노드의 자식 노드를 반복 합니다.This example jumps to the first child node of the root node and then iterates through the child nodes of that node if any exist.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   XmlDocument^ doc = gcnew 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 );
      }
   }
}
using System;
using System.IO;
using System.Xml;

public class Sample {

  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
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 'Main
End Class 'Sample

부모 노드를 다시 가져오기Get back to the parent node

ParentNode 속성을 사용합니다.Use the ParentNode property.

마지막 자식 노드를 참조 하세요Refer to the last child node

이 예제에서는 콘솔에는 책의 가격을 씁니다.This example writes the price of a book to the console. 가격 노드가 책 노드의 마지막 자식입니다.The price node is the last child of a book node.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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 );
}

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

public class Sample {

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

Imports System
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
        
        Console.WriteLine("Display the price element...")
        Console.WriteLine(root.LastChild.OuterXml)
    End Sub 'Main
End Class 'Sample

형제 간 탐색Navigate forward across siblings

이 예제에서는 책 책에서 앞으로 이동 합니다.This example moves forward from book to book. 책 노드는 서로 형제 관계입니다.Book nodes are siblings to one another.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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 );
}

using System;
using System.Xml;

public class Sample {

  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
Imports System.Xml
Imports Microsoft.VisualBasic

public class Sample 

  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

형제에서 뒤로 이동Navigate backwards across siblings

이 예제에서는 이전 버전과에서 책을 책을 이동합니다.This example moves backwards from book to book.

#using <System.Xml.dll>

using namespace System;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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 );
}

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
Imports System.Xml
Imports Microsoft.VisualBasic

public class Sample 

  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

노드 찾기Find nodes

데이터의 하나 이상의 노드를 찾기 위해 가장 인기 있는 방법은 XPath 쿼리 문자열을 사용 하려면 이지만 하나 필요 하지 않은 메서드도 있습니다.The most popular way to find one or more nodes of data is to use an XPath query string, but there are also methods that don't require one.

단일 노드 가져오기Get a single node

이 예제에서는 ISBN 번호를 사용 하 여 책을 찾습니다.This example locates a book by using the ISBN number.

XmlNode ^XMLDOMProcessing::XMLHelperMethods::GetBook(String ^uniqueAttribute, XmlDocument ^doc)
{
	XmlNamespaceManager ^nsmgr = gcnew 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 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 쿼리입니다.The string used in this example is an Xpath query. 여기의 더 많은 예제를 찾을 수 있습니다. XPath 예제합니다.You can find more examples of them here: XPath examples.

사용할 수도 있습니다는 GetElementById 노드를 검색 하려고 합니다.You can also use the GetElementById to retrieve nodes. 이 방법을 사용 하려면 정의 해야 XML 파일의 문서 형식 정의 선언에서 ID입니다.To use this approach, you'll have to define ID's in the document type definition declarations of your XML file.

노드를 가져온 후 자식 노드 또는 특성 값을 가져옵니다.After you get a node, you get the value of attributes or child nodes. 이 예제는는 book 노드를 사용 하 여 수행합니다.This example does that with a book node.

void XMLDOMProcessing::XMLHelperMethods::GetBookInformation
(String ^%title, String ^%ISBN, String ^%publicationDate, String ^%price, String ^%genre, XmlNode ^book)
{
	XmlElement ^bookElement = safe_cast<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 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

노드의 컬렉션을 가져옵니다.Get a collection of nodes

저자의 성과 인 모든 책을 선택 하는이 예제 Austen, 다음의 해당 책 가격을 변경 합니다.This example selects all books where the author's last name is Austen, and then changes the price of those books.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;
int main()
{
   XmlDocument^ doc = gcnew 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.
   System::Collections::IEnumerator^ myEnum = nodeList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      XmlNode^ book = safe_cast<XmlNode^>(myEnum->Current);
      book->LastChild->InnerText = "15.95";
   }

   Console::WriteLine( "Display the modified XML document...." );
   doc->Save( Console::Out );
}

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

public class Sample {

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

또한 노드 이름을 사용 하 여 노드의 컬렉션을 가져올 수 있습니다.You can also get a collection of nodes by using the name of the node. 예를 들어이 예제에서는 모든 책 제목의 컬렉션을 가져옵니다.For example, this example gets a collection of all book titles.

#using <System.Xml.dll>

using namespace System;
using namespace System::IO;
using namespace System::Xml;

int main()
{
   //Create the XmlDocument.
   XmlDocument^ doc = gcnew 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 );
   }
}
using System;
using System.IO;
using System.Xml;

public class Sample
{
  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
Option Strict

Imports System
Imports System.IO
Imports System.Xml

Public Class Sample
    
    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 'Main 
End Class 'Sample

전체 샘플의 경우: XmlDocument 클래스 및 기타 관련된 형식을 사용 하 여 메모리에서 XML 조작Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

자세한 정보: XPath 탐색을 사용하여 노드 선택Learn more: Select Nodes Using XPath Navigation

노드를 편집 합니다.Edit nodes

이 예제에서는 책 노드 및 해당 특성을 편집합니다.This example edits a book node and its attributes.

bool XMLDOMProcessing::XMLHelperMethods::editBook(String ^title, String ^ISBN, String ^publicationDate, String ^genre, String ^price, XmlNode ^book, bool validateNode, bool generateSchema)
{

	XmlElement ^bookElement = safe_cast<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)
	{
		if (validateXML(generateSchema, bookElement->OwnerDocument))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	return true;
}
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 문서에서 노드, 내용 및 값 수정Learn more: Modifying Nodes, Content, and Values in an XML Document

전체 샘플의 경우: XmlDocument 클래스 및 기타 관련된 형식을 사용 하 여 메모리에서 XML 조작Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

노드 추가Add nodes

노드를 추가 하려면 사용 합니다 CreateElement 메서드 또는 CreateNode 메서드.To add a node, use the CreateElement method or the CreateNode method.

책 같은 데이터 노드를 추가 하려면 사용 된 CreateElement 메서드.To add a data node such as a book, use the CreateElement method.

다른 유형의 주석, 공백 노드 또는 CDATA 노드를 사용 하는 같은 노드를 CreateNode 메서드.For any other type of node such as a comment, whitespace node, or CDATA node, use the CreateNode method.

책 노드를 만들고 해당 노드로 특성을 추가 합니다. 다음 문서에 해당 노드를 추가 하는이 예제입니다.This example creates a book node, adds attributes to that node, and then adds that node to the document.

XmlElement ^XMLDOMProcessing::XMLHelperMethods::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 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

전체 샘플의 경우: XmlDocument 클래스 및 기타 관련된 형식을 사용 하 여 메모리에서 XML 조작Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

자세한 정보: XML 문서에 노드 삽입Learn more: Inserting Nodes into an XML Document

노드 제거Remove nodes

노드를 제거 하려면 사용 된 RemoveChild 메서드.To remove a node, use the RemoveChild method.

이 예제에서는 책 노드 바로 앞에 나타나는 모든 공백 및 문서에서 책을 제거 합니다.This example removes a book from the document and any whitespace that appears just before the book node.

void XMLDOMProcessing::XMLHelperMethods::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 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

전체 샘플의 경우: XmlDocument 클래스 및 기타 관련된 형식을 사용 하 여 메모리에서 XML 조작Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

자세한 정보: XML 문서에서 노드, 내용 및 값 제거Learn more: Removing Nodes, Content, and Values from an XML Document

위치 노드Position nodes

노드를 사용 하 여 문서에 표시 하려는 선택할 수 있습니다 합니다 InsertBeforeInsertAfter 메서드.You can choose where you want a node to appear in your document by using the InsertBefore and InsertAfter methods.

이 예제에서는 두 가지 도우미 메서드를 보여 줍니다.This example shows two helper methods. 그 중 하나를 목록에서 상위 노드를 이동합니다.One of them moves a node higher in a list. 다른 하위 노드를 이동합니다.The other one moves a node lower.

이러한 메서드는 책 목록에서 책을 위나 아래로 이동할 수 있도록 하는 애플리케이션에서 사용할 수 있습니다.These methods could be used in an application that enables users to move books up and down in a list of books. 사용자는 책을 선택 하 고 위쪽을 누를 때 또는 아래로 단추를 코드 다른 책 노드 전후 해당 책 노드를 배치 하려면 이러한 메서드를 호출할 수 없습니다.When a user chooses a book and presses an up or down button, your code could call methods like these to position the corresponding book node before or after other book nodes.

//************************************************************************************
//
//  Summary: Move elements up in the XML.
//  
//
//************************************************************************************
void XMLDOMProcessing::XMLHelperMethods::MoveElementUp(XmlNode ^book)
{
	XmlNode ^previousNode = book->PreviousSibling;
	while (previousNode != nullptr && (previousNode->NodeType != XmlNodeType::Element))
	{
		previousNode = previousNode->PreviousSibling;
	}
	if (previousNode != nullptr)
	{
		XmlNode ^newLineNode = book->NextSibling;
		book->OwnerDocument->DocumentElement->RemoveChild(book);
		if (newLineNode->NodeType == XmlNodeType::Whitespace || newLineNode->NodeType == XmlNodeType::SignificantWhitespace)
		{
			newLineNode->OwnerDocument->DocumentElement->RemoveChild(newLineNode);
		}
		InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionAbove, previousNode, false, false);
	}
}

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

		InsertBookElement(safe_cast<XmlElement^>(book), Constants::positionBelow, NextNode, false, false);
	}

}
//************************************************************************************
//
//  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

전체 샘플의 경우: XmlDocument 클래스 및 기타 관련된 형식을 사용 하 여 메모리에서 XML 조작Complete sample: Manipulate XML in-Memory by using the XmlDocument class and other related types

생성자

XmlDocument() XmlDocument() XmlDocument() XmlDocument()

XmlDocument 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlDocument class.

XmlDocument(XmlImplementation) XmlDocument(XmlImplementation) XmlDocument(XmlImplementation) XmlDocument(XmlImplementation)

지정된 XmlDocument를 사용하여 XmlImplementation 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlDocument class with the specified XmlImplementation.

XmlDocument(XmlNameTable) XmlDocument(XmlNameTable) XmlDocument(XmlNameTable) XmlDocument(XmlNameTable)

지정된 XmlDocument를 사용하여 XmlNameTable 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the XmlDocument class with the specified XmlNameTable.

속성

Attributes Attributes Attributes Attributes

이 노드의 특성이 포함된 XmlAttributeCollection을 가져옵니다.Gets an XmlAttributeCollection containing the attributes of this node.

(Inherited from XmlNode)
BaseURI BaseURI BaseURI BaseURI

현재 노드의 기본 URI를 가져옵니다.Gets the base URI of the current node.

ChildNodes ChildNodes ChildNodes ChildNodes

노드의 모든 자식을 가져옵니다.Gets all the child nodes of the node.

(Inherited from XmlNode)
DocumentElement DocumentElement DocumentElement DocumentElement

문서의 루트 XmlElement를 가져옵니다.Gets the root XmlElement for the document.

DocumentType DocumentType DocumentType DocumentType

DOCTYPE 선언이 포함된 노드를 가져옵니다.Gets the node containing the DOCTYPE declaration.

FirstChild FirstChild FirstChild FirstChild

노드의 첫 번째 자식을 가져옵니다.Gets the first child of the node.

(Inherited from XmlNode)
HasChildNodes HasChildNodes HasChildNodes HasChildNodes

이 노드에 자식 노드가 있는지를 나타내는 값을 가져옵니다.Gets a value indicating whether this node has any child nodes.

(Inherited from XmlNode)
Implementation Implementation Implementation Implementation

현재 문서에 대한 XmlImplementation 개체를 가져옵니다.Gets the XmlImplementation object for the current document.

InnerText InnerText InnerText InnerText

모든 경우에 InvalidOperationException을 throw합니다.Throws an InvalidOperationException in all cases.

InnerXml InnerXml InnerXml InnerXml

현재 노드의 자식을 나타내는 태그를 가져오거나 설정합니다.Gets or sets the markup representing the children of the current node.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

현재 노드가 읽기 전용인지를 나타내는 값을 가져옵니다.Gets a value indicating whether the current node is read-only.

Item[String, String] Item[String, String] Item[String, String] Item[String, String]

지정된 LocalNameNamespaceURI를 갖고 있는 첫 번째 자식 요소를 가져옵니다.Gets the first child element with the specified LocalName and NamespaceURI.

(Inherited from XmlNode)
Item[String] Item[String] Item[String] Item[String]

지정된 Name을 가진 첫 번째 자식 요소를 가져옵니다.Gets the first child element with the specified Name.

(Inherited from XmlNode)
LastChild LastChild LastChild LastChild

노드의 마지막 자식을 가져옵니다.Gets the last child of the node.

(Inherited from XmlNode)
LocalName LocalName LocalName LocalName

노드의 로컬 이름을 가져옵니다.Gets the local name of the node.

Name Name Name Name

노드의 정규화된 이름을 가져옵니다.Gets the qualified name of the node.

NamespaceURI NamespaceURI NamespaceURI NamespaceURI

이 노드의 네임스페이스 URI를 가져옵니다.Gets the namespace URI of this node.

(Inherited from XmlNode)
NameTable NameTable NameTable NameTable

이 구현과 관련된 XmlNameTable을 가져옵니다.Gets the XmlNameTable associated with this implementation.

NextSibling NextSibling NextSibling NextSibling

이 노드 바로 다음에 오는 노드를 가져옵니다.Gets the node immediately following this node.

(Inherited from XmlNode)
NodeType NodeType NodeType NodeType

현재 노드의 형식을 가져옵니다.Gets the type of the current node.

OuterXml OuterXml OuterXml OuterXml

이 노드와 모든 자식 노드를 포함하는 태그를 가져옵니다.Gets the markup containing this node and all its child nodes.

(Inherited from XmlNode)
OwnerDocument OwnerDocument OwnerDocument OwnerDocument

현재 노드가 속하는 XmlDocument를 가져옵니다.Gets the XmlDocument to which the current node belongs.

ParentNode ParentNode ParentNode ParentNode

부모가 있을 수 있는 노드의 경우 이 노드의 부모 노드를 가져옵니다.Gets the parent node of this node (for nodes that can have parents).

Prefix Prefix Prefix Prefix

이 노드의 네임스페이스 접두사를 가져오거나 설정합니다.Gets or sets the namespace prefix of this node.

(Inherited from XmlNode)
PreserveWhitespace PreserveWhitespace PreserveWhitespace PreserveWhitespace

요소 콘텐츠에서 공백을 유지할지를 나타내는 값을 가져오거나 설정합니다.Gets or sets a value indicating whether to preserve white space in element content.

PreviousSibling PreviousSibling PreviousSibling PreviousSibling

이 노드 바로 앞에 있는 노드를 가져옵니다.Gets the node immediately preceding this node.

(Inherited from XmlNode)
PreviousText PreviousText PreviousText PreviousText

이 노드 바로 앞에 있는 텍스트 노드를 가져옵니다.Gets the text node that immediately precedes this node.

(Inherited from XmlNode)
SchemaInfo SchemaInfo SchemaInfo SchemaInfo

노드의 PSVI(스키마 유효성 검사 이후 정보 집합)를 반환합니다.Returns the Post-Schema-Validation-Infoset (PSVI) of the node.

Schemas Schemas Schemas Schemas

XmlDocument에 연결된 XmlSchemaSet 개체를 가져오거나 설정합니다.Gets or sets the XmlSchemaSet object associated with this XmlDocument.

Value Value Value Value

노드의 값을 가져오거나 설정합니다.Gets or sets the value of the node.

(Inherited from XmlNode)
XmlResolver XmlResolver XmlResolver XmlResolver

외부 리소스 확인을 위해 사용할 XmlResolver를 설정합니다.Sets the XmlResolver to use for resolving external resources.

메서드

AppendChild(XmlNode) AppendChild(XmlNode) AppendChild(XmlNode) AppendChild(XmlNode)

지정된 노드를 이 노드의 자식 노드 목록 끝에 추가합니다.Adds the specified node to the end of the list of child nodes, of this node.

(Inherited from XmlNode)
Clone() Clone() Clone() Clone()

이 노드의 복제본을 만듭니다.Creates a duplicate of this node.

(Inherited from XmlNode)
CloneNode(Boolean) CloneNode(Boolean) CloneNode(Boolean) CloneNode(Boolean)

이 노드의 복제본을 만듭니다.Creates a duplicate of this node.

CreateAttribute(String) CreateAttribute(String) CreateAttribute(String) CreateAttribute(String)

지정된 Name을 가진 XmlAttribute를 만듭니다.Creates an XmlAttribute with the specified Name.

CreateAttribute(String, String) CreateAttribute(String, String) CreateAttribute(String, String) CreateAttribute(String, String)

지정된 정규화된 이름과 NamespaceURI가 있는 XmlAttribute를 만듭니다.Creates an XmlAttribute with the specified qualified name and NamespaceURI.

CreateAttribute(String, String, String) CreateAttribute(String, String, String) CreateAttribute(String, String, String) CreateAttribute(String, String, String)

지정된 Prefix, LocalNameNamespaceURI가 있는 XmlAttribute를 만듭니다.Creates an XmlAttribute with the specified Prefix, LocalName, and NamespaceURI.

CreateCDataSection(String) CreateCDataSection(String) CreateCDataSection(String) CreateCDataSection(String)

지정된 데이터가 포함된 XmlCDataSection를 만듭니다.Creates an XmlCDataSection containing the specified data.

CreateComment(String) CreateComment(String) CreateComment(String) CreateComment(String)

지정된 데이터가 포함된 XmlComment를 만듭니다.Creates an XmlComment containing the specified data.

CreateDefaultAttribute(String, String, String) CreateDefaultAttribute(String, String, String) CreateDefaultAttribute(String, String, String) CreateDefaultAttribute(String, String, String)

지정된 접두사, 로컬 이름 및 네임스페이스 URI가 있는 기본 특성을 만듭니다.Creates a default attribute with the specified prefix, local name and namespace URI.

CreateDocumentFragment() CreateDocumentFragment() CreateDocumentFragment() CreateDocumentFragment()

XmlDocumentFragment를 만듭니다.Creates an XmlDocumentFragment.

CreateDocumentType(String, String, String, String) CreateDocumentType(String, String, String, String) CreateDocumentType(String, String, String, String) CreateDocumentType(String, String, String, String)

XmlDocumentType 개체를 반환합니다.Returns a new XmlDocumentType object.

CreateElement(String) CreateElement(String) CreateElement(String) CreateElement(String)

지정된 이름을 가진 요소를 만듭니다.Creates an element with the specified name.

CreateElement(String, String) CreateElement(String, String) CreateElement(String, String) CreateElement(String, String)

정규화된 이름과 NamespaceURI를 가진 XmlElement를 만듭니다.Creates an XmlElement with the qualified name and NamespaceURI.

CreateElement(String, String, String) CreateElement(String, String, String) CreateElement(String, String, String) CreateElement(String, String, String)

지정된 Prefix, LocalNameNamespaceURI가 있는 요소를 만듭니다.Creates an element with the specified Prefix, LocalName, and NamespaceURI.

CreateEntityReference(String) CreateEntityReference(String) CreateEntityReference(String) CreateEntityReference(String)

지정된 이름을 가진 XmlEntityReference를 만듭니다.Creates an XmlEntityReference with the specified name.

CreateNavigator() CreateNavigator() CreateNavigator() CreateNavigator()

이 문서를 탐색하기 위한 새로운 XPathNavigator 개체를 만듭니다.Creates a new XPathNavigator object for navigating this document.

CreateNavigator(XmlNode) CreateNavigator(XmlNode) CreateNavigator(XmlNode) CreateNavigator(XmlNode)

지정된 XmlNode에 있는 이 문서를 탐색하기 위한 XPathNavigator 개체를 만듭니다.Creates an XPathNavigator object for navigating this document positioned on the XmlNode specified.

CreateNode(String, String, String) CreateNode(String, String, String) CreateNode(String, String, String) CreateNode(String, String, String)

지정된 노드 형식, NameNamespaceURI가 있는 XmlNode를 만듭니다.Creates an XmlNode with the specified node type, Name, and NamespaceURI.

CreateNode(XmlNodeType, String, String) CreateNode(XmlNodeType, String, String) CreateNode(XmlNodeType, String, String) CreateNode(XmlNodeType, String, String)

지정된 XmlNodeType, NameNamespaceURI가 있는 XmlNode를 만듭니다.Creates an XmlNode with the specified XmlNodeType, Name, and NamespaceURI.

CreateNode(XmlNodeType, String, String, String) CreateNode(XmlNodeType, String, String, String) CreateNode(XmlNodeType, String, String, String) CreateNode(XmlNodeType, String, String, String)

지정된 XmlNodeType, Prefix, NameNamespaceURI가 있는 XmlNode를 만듭니다.Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.

CreateProcessingInstruction(String, String) CreateProcessingInstruction(String, String) CreateProcessingInstruction(String, String) CreateProcessingInstruction(String, String)

지정된 이름과 데이터가 있는 XmlProcessingInstruction을 만듭니다.Creates an XmlProcessingInstruction with the specified name and data.

CreateSignificantWhitespace(String) CreateSignificantWhitespace(String) CreateSignificantWhitespace(String) CreateSignificantWhitespace(String)

XmlSignificantWhitespace 노드를 만듭니다.Creates an XmlSignificantWhitespace node.

CreateTextNode(String) CreateTextNode(String) CreateTextNode(String) CreateTextNode(String)

지정된 텍스트가 있는 XmlText를 만듭니다.Creates an XmlText with the specified text.

CreateWhitespace(String) CreateWhitespace(String) CreateWhitespace(String) CreateWhitespace(String)

XmlWhitespace 노드를 만듭니다.Creates an XmlWhitespace node.

CreateXmlDeclaration(String, String, String) CreateXmlDeclaration(String, String, String) CreateXmlDeclaration(String, String, String) CreateXmlDeclaration(String, String, String)

지정된 값이 있는 XmlDeclaration 노드를 만듭니다.Creates an XmlDeclaration node with the specified values.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetElementById(String) GetElementById(String) GetElementById(String) GetElementById(String)

지정된 ID의 XmlElement를 가져옵니다.Gets the XmlElement with the specified ID.

GetElementsByTagName(String) GetElementsByTagName(String) GetElementsByTagName(String) GetElementsByTagName(String)

지정된 Name과 일치하는 모든 하위 요소의 목록이 포함된 XmlNodeList를 반환합니다.Returns an XmlNodeList containing a list of all descendant elements that match the specified Name.

GetElementsByTagName(String, String) GetElementsByTagName(String, String) GetElementsByTagName(String, String) GetElementsByTagName(String, String)

지정된 LocalNameNamespaceURI와 일치하는 모든 하위 요소의 목록이 포함된 XmlNodeList를 반환합니다.Returns an XmlNodeList containing a list of all descendant elements that match the specified LocalName and NamespaceURI.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

현재 노드에서 자식 노드를 반복하는 열거자를 가져옵니다.Gets an enumerator that iterates through the child nodes in the current node.

(Inherited from XmlNode)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(Inherited from Object)
GetNamespaceOfPrefix(String) GetNamespaceOfPrefix(String) GetNamespaceOfPrefix(String) GetNamespaceOfPrefix(String)

현재 노드의 범위에 있는 지정된 접두사에 대해 가장 가까운 xmlns 선언을 조회하여 선언의 네임스페이스 URI를 반환합니다.Looks up the closest xmlns declaration for the given prefix that is in scope for the current node and returns the namespace URI in the declaration.

(Inherited from XmlNode)
GetPrefixOfNamespace(String) GetPrefixOfNamespace(String) GetPrefixOfNamespace(String) GetPrefixOfNamespace(String)

현재 노드의 범위에 있는 지정된 네임스페이스 URI에 대해 가장 가까운 xmlns 선언을 조회하여 해당 선언에 정의된 접두사를 반환합니다.Looks up the closest xmlns declaration for the given namespace URI that is in scope for the current node and returns the prefix defined in that declaration.

(Inherited from XmlNode)
GetType() GetType() GetType() GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(Inherited from Object)
ImportNode(XmlNode, Boolean) ImportNode(XmlNode, Boolean) ImportNode(XmlNode, Boolean) ImportNode(XmlNode, Boolean)

다른 문서에서 현재 문서로 노드를 가져옵니다.Imports a node from another document to the current document.

InsertAfter(XmlNode, XmlNode) InsertAfter(XmlNode, XmlNode) InsertAfter(XmlNode, XmlNode) InsertAfter(XmlNode, XmlNode)

지정된 노드를 지정된 참조 노드 바로 다음에 삽입합니다.Inserts the specified node immediately after the specified reference node.

(Inherited from XmlNode)
InsertBefore(XmlNode, XmlNode) InsertBefore(XmlNode, XmlNode) InsertBefore(XmlNode, XmlNode) InsertBefore(XmlNode, XmlNode)

지정된 노드를 지정된 참조 노드 바로 앞에 삽입합니다.Inserts the specified node immediately before the specified reference node.

(Inherited from XmlNode)
Load(Stream) Load(Stream) Load(Stream) Load(Stream)

지정된 스트림에서 XML 문서를 로드합니다.Loads the XML document from the specified stream.

Load(String) Load(String) Load(String) Load(String)

지정된 URL에서 XML 문서를 로드합니다.Loads the XML document from the specified URL.

Load(TextReader) Load(TextReader) Load(TextReader) Load(TextReader)

지정된 TextReader에서 XML 문서를 로드합니다.Loads the XML document from the specified TextReader.

Load(XmlReader) Load(XmlReader) Load(XmlReader) Load(XmlReader)

지정된 XmlReader에서 XML 문서를 로드합니다.Loads the XML document from the specified XmlReader.

LoadXml(String) LoadXml(String) LoadXml(String) LoadXml(String)

지정된 문자열에서 XML 문서를 로드합니다.Loads the XML document from the specified string.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(Inherited from Object)
Normalize() Normalize() Normalize() Normalize()

이 XmlNode 아래 전체 수준의 하위 트리에 있는 모든 XmlText 노드를 태그(즉, 태그, 주석, 처리 명령, CDATA 섹션 및 엔터티 참조)만이 XmlText 노드를 구분하는, 인접한 XmlText 노드가 없는 "정상적인" 폼에 넣습니다.Puts all XmlText nodes in the full depth of the sub-tree underneath this XmlNode into a "normal" form where only markup (that is, tags, comments, processing instructions, CDATA sections, and entity references) separates XmlText nodes, that is, there are no adjacent XmlText nodes.

(Inherited from XmlNode)
PrependChild(XmlNode) PrependChild(XmlNode) PrependChild(XmlNode) PrependChild(XmlNode)

지정된 노드를 이 노드의 자식 노드 목록 앞에 추가합니다.Adds the specified node to the beginning of the list of child nodes for this node.

(Inherited from XmlNode)
ReadNode(XmlReader) ReadNode(XmlReader) ReadNode(XmlReader) ReadNode(XmlReader)

XmlNode의 내용을 기준으로 XmlReader 개체를 만듭니다.Creates an XmlNode object based on the information in the XmlReader. 판독기는 노드나 특성에 위치해야 합니다.The reader must be positioned on a node or attribute.

RemoveAll() RemoveAll() RemoveAll() RemoveAll()

현재 노드의 모든 자식 노드 및/또는 특성을 제거합니다.Removes all the child nodes and/or attributes of the current node.

(Inherited from XmlNode)
RemoveChild(XmlNode) RemoveChild(XmlNode) RemoveChild(XmlNode) RemoveChild(XmlNode)

지정된 자식 노드를 제거합니다.Removes specified child node.

(Inherited from XmlNode)
ReplaceChild(XmlNode, XmlNode) ReplaceChild(XmlNode, XmlNode) ReplaceChild(XmlNode, XmlNode) ReplaceChild(XmlNode, XmlNode)

oldChild 자식 노드를 newChild 노드로 대체합니다.Replaces the child node oldChild with newChild node.

(Inherited from XmlNode)
Save(Stream) Save(Stream) Save(Stream) Save(Stream)

XML 문서를 지정된 스트림에 저장합니다.Saves the XML document to the specified stream.

Save(String) Save(String) Save(String) Save(String)

XML 문서를 지정된 파일에 저장합니다.Saves the XML document to the specified file. 지정한 파일이 존재하면 이 메서드를 덮어씁니다.If the specified file exists, this method overwrites it.

Save(TextWriter) Save(TextWriter) Save(TextWriter) Save(TextWriter)

XML 문서를 지정된 TextWriter에 저장합니다.Saves the XML document to the specified TextWriter.

Save(XmlWriter) Save(XmlWriter) Save(XmlWriter) Save(XmlWriter)

XML 문서를 지정된 XmlWriter에 저장합니다.Saves the XML document to the specified XmlWriter.

SelectNodes(String) SelectNodes(String) SelectNodes(String) SelectNodes(String)

XPath 식과 일치하는 노드의 목록을 선택합니다.Selects a list of nodes matching the XPath expression.

(Inherited from XmlNode)
SelectNodes(String, XmlNamespaceManager) SelectNodes(String, XmlNamespaceManager) SelectNodes(String, XmlNamespaceManager) SelectNodes(String, XmlNamespaceManager)

XPath 식과 일치하는 노드의 목록을 선택합니다.Selects a list of nodes matching the XPath expression. XPath 식에 있는 접두사는 제공된 XmlNamespaceManager를 사용해 확인합니다.Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager.

(Inherited from XmlNode)
SelectSingleNode(String) SelectSingleNode(String) SelectSingleNode(String) SelectSingleNode(String)

XPath 식과 일치하는 첫 번째 XmlNode를 선택해야 합니다.Selects the first XmlNode that matches the XPath expression.

(Inherited from XmlNode)
SelectSingleNode(String, XmlNamespaceManager) SelectSingleNode(String, XmlNamespaceManager) SelectSingleNode(String, XmlNamespaceManager) SelectSingleNode(String, XmlNamespaceManager)

XPath 식과 일치하는 첫 번째 XmlNode를 선택해야 합니다.Selects the first XmlNode that matches the XPath expression. XPath 식에 있는 접두사는 제공된 XmlNamespaceManager를 사용해 확인합니다.Any prefixes found in the XPath expression are resolved using the supplied XmlNamespaceManager.

(Inherited from XmlNode)
Supports(String, String) Supports(String, String) Supports(String, String) Supports(String, String)

DOM 구현에서 특정 기능을 구현하는지 테스트합니다.Tests if the DOM implementation implements a specific feature.

(Inherited from XmlNode)
ToString() ToString() ToString() ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)
Validate(ValidationEventHandler) Validate(ValidationEventHandler) Validate(ValidationEventHandler) Validate(ValidationEventHandler)

Schemas 속성에 포함된 XSD(XML 스키마 정의) 언어 스키마를 기준으로 XmlDocument의 유효성을 검사합니다.Validates the XmlDocument against the XML Schema Definition Language (XSD) schemas contained in the Schemas property.

Validate(ValidationEventHandler, XmlNode) Validate(ValidationEventHandler, XmlNode) Validate(ValidationEventHandler, XmlNode) Validate(ValidationEventHandler, XmlNode)

Schemas 속성에 포함된 XSD(XML 스키마 정의) 언어 스키마를 기준으로, 지정된 XmlNode 개체의 유효성을 검사합니다.Validates the XmlNode object specified against the XML Schema Definition Language (XSD) schemas in the Schemas property.

WriteContentTo(XmlWriter) WriteContentTo(XmlWriter) WriteContentTo(XmlWriter) WriteContentTo(XmlWriter)

XmlDocument 노드의 모든 자식을 지정된 XmlWriter에 저장합니다.Saves all the children of the XmlDocument node to the specified XmlWriter.

WriteTo(XmlWriter) WriteTo(XmlWriter) WriteTo(XmlWriter) WriteTo(XmlWriter)

XmlDocument 노드를 지정된 XmlWriter에 저장합니다.Saves the XmlDocument node to the specified XmlWriter.

이벤트

NodeChanged NodeChanged NodeChanged NodeChanged

이 문서에 속하는 노드의 Value가 변경된 경우에 발생합니다.Occurs when the Value of a node belonging to this document has been changed.

NodeChanging NodeChanging NodeChanging NodeChanging

이 문서에 속하는 노드의 Value를 변경할 경우에 발생합니다.Occurs when the Value of a node belonging to this document is about to be changed.

NodeInserted NodeInserted NodeInserted NodeInserted

이 문서에 속하는 노드를 다른 노드에 삽입한 경우에 발생합니다.Occurs when a node belonging to this document has been inserted into another node.

NodeInserting NodeInserting NodeInserting NodeInserting

이 문서에 속하는 노드를 다른 노드에 삽입할 경우에 발생합니다.Occurs when a node belonging to this document is about to be inserted into another node.

NodeRemoved NodeRemoved NodeRemoved NodeRemoved

이 문서에 속하는 노드를 부모에서 제거한 경우에 발생합니다.Occurs when a node belonging to this document has been removed from its parent.

NodeRemoving NodeRemoving NodeRemoving NodeRemoving

이 문서에 속하는 노드를 문서에서 제거할 경우에 발생합니다.Occurs when a node belonging to this document is about to be removed from the document.

명시적 인터페이스 구현

ICloneable.Clone() ICloneable.Clone() ICloneable.Clone() ICloneable.Clone()

이 멤버에 대한 설명은 Clone()를 참조하세요.For a description of this member, see Clone().

(Inherited from XmlNode)
IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

이 멤버에 대한 설명은 GetEnumerator()를 참조하십시오.For a description of this member, see GetEnumerator().

(Inherited from XmlNode)

Extension Methods

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

요소를 캐스팅을 IEnumerable 를 지정 된 형식입니다.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

요소를 필터링 하는 IEnumerable 지정된 된 형식에 기반 합니다.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

쿼리를 병렬화할 수 있도록 합니다.Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

변환를 IEnumerableIQueryable합니다.Converts an IEnumerable to an IQueryable.

CreateNavigator(XmlDocument) CreateNavigator(XmlDocument) CreateNavigator(XmlDocument) CreateNavigator(XmlDocument)
CreateNavigator(XmlDocument, XmlNode) CreateNavigator(XmlDocument, XmlNode) CreateNavigator(XmlDocument, XmlNode) CreateNavigator(XmlDocument, XmlNode)
CreateNavigator(XmlNode) CreateNavigator(XmlNode) CreateNavigator(XmlNode) CreateNavigator(XmlNode)
SelectNodes(XmlNode, String) SelectNodes(XmlNode, String) SelectNodes(XmlNode, String) SelectNodes(XmlNode, String)
SelectNodes(XmlNode, String, XmlNamespaceManager) SelectNodes(XmlNode, String, XmlNamespaceManager) SelectNodes(XmlNode, String, XmlNamespaceManager) SelectNodes(XmlNode, String, XmlNamespaceManager)
SelectSingleNode(XmlNode, String) SelectSingleNode(XmlNode, String) SelectSingleNode(XmlNode, String) SelectSingleNode(XmlNode, String)
SelectSingleNode(XmlNode, String, XmlNamespaceManager) SelectSingleNode(XmlNode, String, XmlNamespaceManager) SelectSingleNode(XmlNode, String, XmlNamespaceManager) SelectSingleNode(XmlNode, String, XmlNamespaceManager)
ToXPathNavigable(XmlNode) ToXPathNavigable(XmlNode) ToXPathNavigable(XmlNode) ToXPathNavigable(XmlNode)

적용 대상

추가 정보