XmlDocument Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Representa um documento XML. Você pode usar essa classe para carregar, validar, editar, adicionar e posicionar o XML em um documento.
public ref class XmlDocument : System::Xml::XmlNode
public class XmlDocument : System.Xml.XmlNode
type XmlDocument = class
inherit XmlNode
Public Class XmlDocument
Inherits XmlNode
- Herança
- Derivado
Comentários
A XmlDocument classe é uma representação na memória de um documento XML. Ele implementa o W3C XML Document Object Model (DOM) Nível 1 Core e o Nível 2 do DOM Principal.
DOM significa modelo de objeto de documento. Para ler mais sobre isso, consulte O DOM (Modelo de Objeto de Documento XML).
Você pode carregar XML no DOM usando a XmlDocument classe e, em seguida, ler, modificar e remover XML programaticamente no documento.
Se você quiser abrir a XmlDocument classe e ver como ela é implementada, consulte a Fonte de Referência.
Tarefas
Carregar XML no modelo de objeto do documento
Comece com um documento XML como este que tem alguns livros em uma coleção. Ele contém as coisas básicas que você encontraria em qualquer documento XML, incluindo um namespace, elementos que representam dados e atributos que descrevem os dados.
<?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>
Em seguida, carregue esses dados no DOM para que você possa trabalhar com eles na memória. A maneira mais popular de fazer isso é consultar um arquivo em seu computador local ou em uma rede.
Este exemplo carrega XML de um arquivo. Se o arquivo não existir, ele apenas gerará algum XML e carregará isso.
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
Saiba mais: Lendo um documento XML no DOM
Validá-lo em um esquema
Comece com um esquema XML como este. Esse esquema define os tipos de dados no XML e quais atributos são necessários.
<?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>
Crie um XmlReader objeto usando seu esquema e carregue esse objeto no DOM. Crie um manipulador de eventos que é executado quando o código tenta modificar o arquivo XML de maneiras que violam as regras do esquema.
Esses blocos de código mostram métodos auxiliares que fazem tudo isso.
//************************************************************************************
//
// 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
Saiba mais: Validando um documento XML no DOM
Navegar na árvore de documentos
Você pode usar propriedades para navegar por um documento XML. Mas antes de usar qualquer um deles, vamos examinar rapidamente alguns termos. Seu documento é composto por nós. Cada nó tem como nó pai único diretamente acima dele. O único nó que não tem um nó pai é a raiz do documento, pois é o nó de nível superior. A maioria dos nós pode ter nós filho , que são nós diretamente abaixo deles. Nós que estão no mesmo nível são irmãos.
Os exemplos a seguir mostram como obter o nó raiz, ir para o primeiro nó filho do nó raiz, acessar qualquer um de seus nós filho, voltar para o nó pai e, em seguida, navegar por nós irmãos.
Começar com o nó raiz
Este exemplo obtém o nó raiz e usa esse nó para gerar o conteúdo do documento para o 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.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
End Class
Obter nós filho
Este exemplo salta para o primeiro nó filho do nó raiz e, em seguida, itera pelos nós filho desse nó se houver algum.
#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.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
Voltar para o nó pai
Use a propriedade ParentNode.
Consulte o último nó filho
Este exemplo grava o preço de um livro no console. O nó de preço é o último filho de um nó de livro.
#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.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
Option Strict
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
End Class
Navegar para a frente entre irmãos
Este exemplo avança de livro para livro. Nós de livro são irmãos uns dos outros.
#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 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 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
Navegar para trás entre irmãos
Este exemplo se move para trás de livro para livro.
#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.Xml
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
Localizar nós
A maneira mais popular de encontrar um ou mais nós de dados é usar uma cadeia de caracteres de consulta XPath, mas também há métodos que não exigem um.
Obter um único nó
Este exemplo localiza um livro usando o número ISBN.
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
A cadeia de caracteres usada neste exemplo é uma consulta Xpath. Você pode encontrar mais exemplos deles aqui: exemplos de XPath.
Você também pode usar o GetElementById para recuperar nós. Para usar essa abordagem, você precisará definir IDs nas declarações de definição de tipo de documento do arquivo XML.
Depois de obter um nó, você obtém o valor de atributos ou nós filho. Este exemplo faz isso com um nó de livro.
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
Obter uma coleção de nós
Este exemplo seleciona todos os livros em que o sobrenome do autor é Austen e, em seguida, altera o preço desses livros.
#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.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
Você também pode obter uma coleção de nós usando o nome do nó. Por exemplo, este exemplo obtém uma coleção de todos os títulos de livro.
#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.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
Option Strict
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
End Class
Saiba mais: Selecionar nós usando a navegação XPath
Editar nós
Este exemplo edita um nó de livro e seus atributos.
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
Saiba mais: Modificando nós, conteúdo e valores em um documento XML
Adicionar nós
Para adicionar um nó, use o CreateElement método ou o CreateNode método.
Para adicionar um nó de dados, como um livro, use o CreateElement método.
Para qualquer outro tipo de nó, como um comentário, um nó de espaço em branco ou um nó CDATA, use o CreateNode método.
Este exemplo cria um nó de livro, adiciona atributos a esse nó e adiciona esse nó ao documento.
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
Saiba mais: Inserindo nós em um documento XML
Remover nós
Para remover um nó, use o RemoveChild método.
Este exemplo remove um livro do documento e de qualquer espaço em branco que aparece pouco antes do nó do livro.
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
Saiba mais: Removendo nós, conteúdo e valores de um documento XML
Nós de posição
Você pode escolher onde deseja que um nó apareça em seu documento usando os métodos e InsertAfter os InsertBefore métodos.
Este exemplo mostra dois métodos auxiliares. Um deles move um nó mais alto em uma lista. O outro move um nó para baixo.
Esses métodos podem ser usados em um aplicativo que permite aos usuários mover livros para cima e para baixo em uma lista de livros. Quando um usuário escolhe um livro e pressiona um botão para cima ou para baixo, seu código pode chamar métodos como esses para posicionar o nó do livro correspondente antes ou depois de outros nós do livro.
//************************************************************************************
//
// 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
Construtores
XmlDocument() |
Inicializa uma nova instância da classe XmlDocument. |
XmlDocument(XmlImplementation) |
Inicializa uma nova instância da classe |
XmlDocument(XmlNameTable) |
Inicializa uma nova instância da classe |
Propriedades
Attributes |
Obtém um XmlAttributeCollection que contém os atributos desse nó. (Herdado de XmlNode) |
BaseURI |
Obtém o URI base do nó atual. |
ChildNodes |
Obtém todos os nós filho do nó. (Herdado de XmlNode) |
DocumentElement |
Obtém a raiz XmlElement para o documento. |
DocumentType |
Obtém o nó que contém a declaração DOCTYPE. |
FirstChild |
Obtém o primeiro filho do nó. (Herdado de XmlNode) |
HasChildNodes |
Obtém um valor que indica se este nó tem nós filho. (Herdado de XmlNode) |
Implementation |
Obtém o objeto XmlImplementation para o documento atual. |
InnerText |
Aciona um InvalidOperationException em todos os casos. |
InnerText |
Obtém ou define os valores concatenados do nó e todos os seus nós filho. (Herdado de XmlNode) |
InnerXml |
Obtém ou define a marcação que representa os filhos do nó atual. |
IsReadOnly |
Obtém um valor que indica se o nó atual é somente leitura. |
Item[String, String] |
Obtém o primeiro elemento filho com o LocalName e o NamespaceURI especificados. (Herdado de XmlNode) |
Item[String] |
Obtém o primeiro elemento filho com o Name especificado. (Herdado de XmlNode) |
LastChild |
Obtém o último filho do nó. (Herdado de XmlNode) |
LocalName |
Obtém o nome local do nó. |
Name |
Obtém o nome qualificado do nó. |
NamespaceURI |
Obtém o URI do namespace deste nó. (Herdado de XmlNode) |
NameTable |
Obtém o XmlNameTable associado à essa implementação. |
NextSibling |
Obtém o nó imediatamente posterior a este nó. (Herdado de XmlNode) |
NodeType |
Obtém o tipo do nó atual. |
OuterXml |
Obtém a marcação que contém esse nó e todos os nós filho. (Herdado de XmlNode) |
OwnerDocument |
Obtém o XmlDocument ao qual pertence o nó atual. |
ParentNode |
Obtém o nó pai desse nó (para os nós que podem ter pais). |
ParentNode |
Obtém o pai deste nó (para os nós que podem ter pais). (Herdado de XmlNode) |
Prefix |
Obtém ou define o prefixo de namespace desse nó. (Herdado de XmlNode) |
PreserveWhitespace |
Obtém ou define um valor que indica se os espaços em branco devem ser preservados no conteúdo do elemento. |
PreviousSibling |
Obtém o nó imediatamente anterior a este nó. (Herdado de XmlNode) |
PreviousText |
Obtém o nó de texto que precede imediatamente este nó. (Herdado de XmlNode) |
SchemaInfo |
Retorna o PSVI (Post-Schema-Validation-Infoset) do nó. |
SchemaInfo |
Obtém o infoset de validação de esquema de postagem que foi atribuído a esse nó como resultado da validação de esquema. (Herdado de XmlNode) |
Schemas |
Obtém ou define o objeto XmlSchemaSet associado a esse XmlDocument. |
Value |
Obtém ou define o valor do nó. (Herdado de XmlNode) |
XmlResolver |
Define o XmlResolver que será usado para resolver recursos externos. |
Métodos
AppendChild(XmlNode) |
Adiciona o nó especificado ao final da lista de nós filho desse nó. (Herdado de XmlNode) |
Clone() |
Cria uma duplicação deste nó. (Herdado de XmlNode) |
CloneNode(Boolean) |
Cria uma duplicação deste nó. |
CreateAttribute(String) |
Cria um XmlAttribute com o Name especificado. |
CreateAttribute(String, String) |
Cria um XmlAttribute com o nome e dados especificados e NamespaceURI. |
CreateAttribute(String, String, String) |
Cria um XmlAttribute com o Prefix, LocalName e NamespaceURI especificados. |
CreateCDataSection(String) |
Cria um XmlCDataSection que contém os dados especificados. |
CreateComment(String) |
Cria um XmlComment que contém os dados especificados. |
CreateDefaultAttribute(String, String, String) |
Cria um atributo padrão com o prefixo especificado, o nome local e o URI de namespace. |
CreateDocumentFragment() |
Cria um XmlDocumentFragment. |
CreateDocumentType(String, String, String, String) |
Retorna um novo objeto XmlDocumentType. |
CreateElement(String) |
Cria um elemento com o nome especificado. |
CreateElement(String, String) |
Cria um XmlElement com o nome qualificado e NamespaceURI. |
CreateElement(String, String, String) |
Cria um elemento com o Prefix, LocalName e NamespaceURI especificados. |
CreateEntityReference(String) |
Cria um XmlEntityReference com o nome especificado. |
CreateNavigator() |
Cria um novo objeto XPathNavigator para navegar nesse documento. |
CreateNavigator() |
Cria um XPathNavigator para navegar esse objeto. (Herdado de XmlNode) |
CreateNavigator(XmlNode) |
Cria um objeto XPathNavigator para navegar neste documento posicionado no XmlNode especificado. |
CreateNode(String, String, String) |
Cria um XmlNode com o tipo de nó especificado, Name e NamespaceURI. |
CreateNode(XmlNodeType, String, String) |
Cria um XmlNode com o XmlNodeType, Name e NamespaceURI especificados. |
CreateNode(XmlNodeType, String, String, String) |
Cria um XmlNode com o XmlNodeType, Prefix, Name e NamespaceURI especificados. |
CreateProcessingInstruction(String, String) |
Cria um XmlProcessingInstruction com o nome e dados especificados. |
CreateSignificantWhitespace(String) |
Cria um nó XmlSignificantWhitespace. |
CreateTextNode(String) |
Cria um XmlText com o texto especificado. |
CreateWhitespace(String) |
Cria um nó XmlWhitespace. |
CreateXmlDeclaration(String, String, String) |
Cria um nó XmlDeclaration com os valores especificados. |
Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
GetElementById(String) |
Obtém o XmlElement com a ID especificada. |
GetElementsByTagName(String) |
Retorna um XmlNodeList que contém uma lista de todos os elementos descendentes que correspondem ao Name especificado. |
GetElementsByTagName(String, String) |
Retorna um XmlNodeList que contém uma lista de todos os elementos descendentes que correspondem ao LocalName e NamespaceURI especificados. |
GetEnumerator() |
Obtém um enumerador que itera pelos nós filhos do nó atual. (Herdado de XmlNode) |
GetHashCode() |
Serve como a função de hash padrão. (Herdado de Object) |
GetNamespaceOfPrefix(String) |
Procura pela declaração xmlns mais próxima para o prefixo especificado no escopo para o nó atual e retorna o URI de namespace na declaração. (Herdado de XmlNode) |
GetPrefixOfNamespace(String) |
Procura pela declaração xmlns mais próxima para o URI do namespace determinado que esteja no escopo para o nó atual e retorna o prefixo definido nessa declaração. (Herdado de XmlNode) |
GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
ImportNode(XmlNode, Boolean) |
Importa um nó de outro documento para o documento atual. |
InsertAfter(XmlNode, XmlNode) |
Insere o nó especificado imediatamente após o nó de referência especificado. (Herdado de XmlNode) |
InsertBefore(XmlNode, XmlNode) |
Insere o nó especificado imediatamente antes do nó de referência especificado. (Herdado de XmlNode) |
Load(Stream) |
Carrega o documento XML do fluxo especificado. |
Load(String) |
Carrega o documento XML da URL especificada. |
Load(TextReader) |
Carrega o documento XML da TextReader especificada. |
Load(XmlReader) |
Carrega o documento XML da XmlReader especificada. |
LoadXml(String) |
Carrega o documento XML da cadeia de caracteres especificada. |
MemberwiseClone() |
Cria uma cópia superficial do Object atual. (Herdado de Object) |
Normalize() |
Coloca todos os nós XmlText em toda a profundidade da subárvore sob esse XmlNode em uma forma "normal" em que somente a marcação (isto é, marcas, comentários, instruções de processamento, seções CDATA e referências de entidade) separa os nós XmlText, isto é, não existem nós XmlText adjacentes. (Herdado de XmlNode) |
PrependChild(XmlNode) |
Adiciona o nó especificado ao início da lista de nós filho desse nó. (Herdado de XmlNode) |
ReadNode(XmlReader) |
Cria um objeto XmlNode com base nas informações no XmlReader. O leitor deve ser posicionado em um nó ou atributo. |
RemoveAll() |
Remove todos os nós filho e/ou atributos do nó atual. (Herdado de XmlNode) |
RemoveChild(XmlNode) |
Remove o nó filho especificado. (Herdado de XmlNode) |
ReplaceChild(XmlNode, XmlNode) |
Substitui o nó filho |
Save(Stream) |
Salva o documento XML no fluxo especificado. |
Save(String) |
Salva o documento XML no arquivo especificado. Se o arquivo especificado existir, este método o substituirá. |
Save(TextWriter) |
Salva o documento XML no TextWriter especificado. |
Save(XmlWriter) |
Salva o documento XML no XmlWriter especificado. |
SelectNodes(String) |
Seleciona uma lista de nós que correspondem à expressão XPath. (Herdado de XmlNode) |
SelectNodes(String, XmlNamespaceManager) |
Seleciona uma lista de nós que correspondem à expressão XPath. Todos os prefixos encontrados na expressão XPath são resolvidos usando o XmlNamespaceManager fornecido. (Herdado de XmlNode) |
SelectSingleNode(String) |
Seleciona o primeiro |
SelectSingleNode(String, XmlNamespaceManager) |
Seleciona o primeiro |
Supports(String, String) |
Testa se a implementação do DOM implementa um recurso específico. (Herdado de XmlNode) |
ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual. (Herdado de Object) |
Validate(ValidationEventHandler) |
Valida o XmlDocument em relação aos esquemas XSD (Linguagem de Definição de Esquema XML) contidos na propriedade Schemas. |
Validate(ValidationEventHandler, XmlNode) |
Valida o objeto XmlNode especificado para os esquemas de XSD (Linguagem de Definição de Esquema XML) contidos na propriedade Schemas. |
WriteContentTo(XmlWriter) |
Salva todos os filhos do nó |
WriteTo(XmlWriter) |
Salva o nó |
Eventos
NodeChanged |
Ocorre quando o Value de um nó que pertence a este documento foi alterado. |
NodeChanging |
Ocorre quando o Value de um nó que pertence a este documento está prestes a ser alterado. |
NodeInserted |
Ocorre quando um nó que pertence a este documento foi inserido em outro nó. |
NodeInserting |
Ocorre quando um nó que pertence a este documento está prestes a ser inserido em outro nó. |
NodeRemoved |
Ocorre quando um nó que pertence a este documento foi removido do pai dele. |
NodeRemoving |
Ocorre quando um nó que pertence a este documento está prestes a ser removido do documento. |
Implantações explícitas de interface
ICloneable.Clone() |
Para obter uma descrição desse membro, confira Clone(). (Herdado de XmlNode) |
IEnumerable.GetEnumerator() |
Para obter uma descrição desse membro, confira GetEnumerator(). (Herdado de XmlNode) |
Métodos de Extensão
Cast<TResult>(IEnumerable) |
Converte os elementos de um IEnumerable para o tipo especificado. |
OfType<TResult>(IEnumerable) |
Filtra os elementos de um IEnumerable com base em um tipo especificado. |
AsParallel(IEnumerable) |
Habilita a paralelização de uma consulta. |
AsQueryable(IEnumerable) |
Converte um IEnumerable em um IQueryable. |
CreateNavigator(XmlDocument) |
Cria um objeto de navegador XPath para navegar no documento especificado. |
CreateNavigator(XmlDocument, XmlNode) |
Cria um objeto de navegador XPath para navegar no documento especificado posicionado no nó especificado. |
CreateNavigator(XmlNode) |
Cria um navegador XPath para navegar no nó especificado. |
SelectNodes(XmlNode, String) |
Seleciona uma lista de nós que correspondem à expressão XPath especificada. |
SelectNodes(XmlNode, String, XmlNamespaceManager) |
Seleciona uma lista de nós que correspondem à expressão XPath especificada. Todos os prefixos encontrados na expressão XPath são resolvidos usando o gerenciador de namespaces fornecido. |
SelectSingleNode(XmlNode, String) |
Seleciona o primeiro nó que corresponde à expressão XPath. |
SelectSingleNode(XmlNode, String, XmlNamespaceManager) |
Seleciona o primeiro nó que corresponde à expressão XPath. Todos os prefixos encontrados na expressão XPath são resolvidos usando o gerenciador de namespaces fornecido. |
ToXPathNavigable(XmlNode) |
Cria uma instância de IXPathNavigable usada para produzir navegadores. |