Coletânea de Dados Sobre Windows Mobile XML: Última Impressão em
Coletânea de Dados Sobre Windows Mobile XML: Última Impressão em
XmlDocument xmlFile = new XmlDocument(); xmlFile .Load(@"\My Documents\myXML.xml"); XmlNodeList nodeList = xmlFile.GetElementsByTagName("resources"); foreach (XmlElement elem in nodeList) { foreach (XmlElement elem2 in elem.ChildNodes) { //.... do all your stuff here or loop more! <Configuration> <FName>Jack</FName> <SName>Sparrow</SName> </Configuration> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace ReadFromXML { class Program { private const string sXML_File_Path = @"C:\Test\XML_Configuration_File.xml"; static void Main(string[] args) { string sFirstName = GetXmlConfigValue("FName"); string sSecondName = GetXmlConfigValue("SName"); Console.WriteLine(sFirstName + " " + sSecondName); Console.Read(); } public static string GetXmlConfigValue(string sNodeName) { string sNodeValue = ""; XmlDocument xml_Document = null; XmlNodeList xnlNodelist = null; XmlNode xnParent = null; XmlNode xnChild = null; xml_Document = new System.Xml.XmlDocument(); try
//Load the XML document xml_Document.Load(sXML_File_Path); //Find the node by Tagname which should be exactle same as in our XML Configuration xnlNodelist = xml_Document.GetElementsByTagName(sNodeName); //Point to parent node from the Node List(In our example Configuration is the Parent Node. xnParent = xnlNodelist.Item(0); //Point to Child node. xnChild = xnParent.ChildNodes[0]; //Read the value from the child node. sNodeValue = xnChild.InnerText.ToString();
file.
In this article, you will see how to read and write XML documents in Microsoft .NET using C# language. First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa. Introduction to Microsoft .NET XML Namespaces and Classes Before start working with XML document in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library. .NET provides five namespace System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, and System.Xml.Xsl to support XML classes. The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes. The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example. The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas. The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example. The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects. In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList. Next namespace in Xml series is System.Xml.Schema. It classes to work with XML schemas
such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType. The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams. The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation though XML documents. This class contains many Move methods to move through a document. The System.Xml.Xsl namespace contains classes to work with XSL/T transformations. Reading XML Documents In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line: XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); Or you can use any XML file. The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor. XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber an so on. List 1 reads a document and displays a node information using these properties. About Sample Example 1 In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output. Sample Example 1. using System; using System.Xml; namespace ReadXml1 { class Class1 { static void Main(string[] args) { // Create an isntance of XmlTextReader and call Read method to read the file XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); textReader.Read(); // If the node has value
while (textReader.Read()) { // Move to fist element textReader.MoveToElement(); Console.WriteLine("XmlTextReader Properties Test"); Console.WriteLine("==================="); // Read this element's properties and display them on console Console.WriteLine("Name:" + textReader.Name); Console.WriteLine("Base URI:" + textReader.BaseURI); Console.WriteLine("Local Name:" + textReader.LocalName); Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString()); Console.WriteLine("Depth:" + textReader.Depth.ToString()); Console.WriteLine("Line Number:" + textReader.LineNumber.ToString()); Console.WriteLine("Node Type:" + textReader.NodeType.ToString()); Console.WriteLine("Attribute Count:" + textReader.Value.ToString()); }
The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on. List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has. About Sample Example 2 In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document. Sample Example 2. using System; using System.Xml; namespace ReadingXML2 { class Class1 { static void Main(string[] args) { int ws = 0; int pi = 0; int dc = 0; int cc = 0; int ac = 0; int et = 0; int el = 0; int xd = 0; // Read a document XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
// Read until end of file while (textReader.Read()) { XmlNodeType nType = textReader.NodeType; // If node type us a declaration if (nType == XmlNodeType.XmlDeclaration) { Console.WriteLine("Declaration:" + textReader.Name.ToString()); xd = xd + 1; } // if node type is a comment if (nType == XmlNodeType.Comment) { Console.WriteLine("Comment:" + textReader.Name.ToString()); cc = cc + 1; } // if node type us an attribute if (nType == XmlNodeType.Attribute) { Console.WriteLine("Attribute:" + textReader.Name.ToString()); ac = ac + 1; } // if node type is an element if (nType == XmlNodeType.Element) { Console.WriteLine("Element:" + textReader.Name.ToString()); el = el + 1; } // if node type is an entity\ if (nType == XmlNodeType.Entity) { Console.WriteLine("Entity:" + textReader.Name.ToString()); et = et + 1; } // if node type is a Process Instruction if (nType == XmlNodeType.Entity) { Console.WriteLine("Entity:" + textReader.Name.ToString()); pi = pi + 1; } // if node type a document if (nType == XmlNodeType.DocumentType) { Console.WriteLine("Document:" + textReader.Name.ToString()); dc = dc + 1; } // if node type is white space if (nType == XmlNodeType.Whitespace) { Console.WriteLine("WhiteSpace:" + textReader.Name.ToString()); ws = ws + 1; } } // Write the summary Console.WriteLine("Total Comments:" + cc.ToString()); Console.WriteLine("Total Attributes:" + ac.ToString()); Console.WriteLine("Total Elements:" + el.ToString());
Entity:" + et.ToString()); Process Instructions:" + pi.ToString()); Declaration:" + xd.ToString()); DocumentType:" + dc.ToString()); WhiteSpaces:" + ws.ToString());
//'Write the DocumentType node textWriter.WriteDocType("book", Nothing, Nothing, "<!ENTITY h 'softcover'>"); The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 514. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter: After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter. About Sample Example 3 In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items. Sample Example 3. using System; using System.Xml; namespace ReadingXML2 { class Class1 { static void Main(string[] args) { // Create a new file in C:\\ dir XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null); // Opens the document textWriter.WriteStartDocument(); // Write comments textWriter.WriteComment("First Comment XmlTextWriter Sample Example"); textWriter.WriteComment("myXmlFile.xml in root dir"); // Write first element textWriter.WriteStartElement("Student"); textWriter.WriteStartElement("r", "RECORD", "urn:record"); // Write next element textWriter.WriteStartElement("Name", ""); textWriter.WriteString("Student"); textWriter.WriteEndElement(); // Write one more element textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony"); textWriter.WriteEndElement(); // WriteChars char[] ch = new char[3]; ch[0] = 'a'; ch[1] = 'r'; ch[2] = 'c'; textWriter.WriteStartElement("Char"); textWriter.WriteChars(ch, 0, ch.Length); textWriter.WriteEndElement(); // Ends the document. textWriter.WriteEndDocument(); // close writer textWriter.Close();
Using XmlDocument The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article. Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter. About Sample Example 4 This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file. Sample Example 4. //Create the XmlDocument. XmlDocument doc = new XmlDocument(); doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy ex</Name></Student>")); //Save the document to a file. doc.Save("C:\\std.xml"); You can also use Save method to display contents on console if you pass Console.Out as a arameter. For example: doc.Save(Console.Out); About Sample Example 5 Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method argument displays data on the console Sample Example 5. XmlDocument doc = new XmlDocument(); //Load the the document with the last book node. XmlTextReader reader = new XmlTextReader("c:\\books.xml"); reader.Read(); // load reader doc.Load(reader); // Display contents on the console doc.Save(Console.Out); Writing Data from a database to an XML Document Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's
data and write the contents to an XML document. The DataSet class provides method to read a relational database table and write this table to an XML file. You use WriteXml method to write a dataset data to an XML file. In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query. About Sample Example 6 In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter. In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir. Sample Example 6. using System; using System.Xml; using System.Data; using System.Data.OleDb; namespace ReadingXML2 { class Class1 { static void Main(string[] args) { // create a connection OleDbConnection con = new OleDbConnection(); con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb"; // create a data adapter OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con); // create a new dataset DataSet ds = new DataSet(); // fill dataset da.Fill(ds, "Customers"); // write dataset contents to an xml file by calling WriteXml method ds.WriteXml("C:\\OutputXML.xml"); } } }
Summary .NET Framework Library provides a good support to work with XML documents. The XmlReader, XmlWriter and their derived classes contains methods and
properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively. ADO.NET provides functionality to read a database and write its contents to the XML document using data providers and a DataSet object.
Outro : XmlDocument xmlDoc = new XmlDocument(); XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); xmlDoc.AppendChild(dec); XmlTextWriter writer = new XmlTextWriter(@"\My Documents\XMLFile1.xml", null); writer.WriteStartElement("student"); writer.WriteElementString("firstname", textBox1.Text); writer.WriteElementString("lastname", textBox2.Text); writer.writeElementString("date", dateTimePicker1.Text); writer.WriteEndElement(); writer.Close(); xmlDoc.Save("XMLFile1.xml");
Uma das grandes novidades da plataforma .NET verso 3.5 o projeto LINQ que introduz um modelo de programao que permite acessar diretamente uma fonte de dados , documentos XML, estrutura de dados, coleo de objetos, etc. usando uma sintaxe parecida com a linguagem SQL. J escrevi diversos artigos sobre LINQ To SQL , um dos membros do projeto LINQ, e, neste artigo vou dar uma viso resumida sobre o LINQ To XML outro membro integrante do LINQ. O LINQ to XML um provedor de dados LINQ que implementado no namespace System.Xml.LINQ a partir da verso 3.5 da plataforma .NET. Ele fornece um modelo de programao que permite ler, construir e escrever dados XML. Voc pode usar LINQ To XML para realizar consultas LINQ sobre dados no formato XML que podem ser retornados do arquivo de sistemas, de uma URL HTTP remota, de um web service ou partir de qualquer XML em memria existente. O LINQ To XML fornece mais recursos e facilidades para tratar com XML do que a API presente no namespace System.XML(XmlReader/XmlWriter) da verso anterior da plataforma .NET, sendo tambm mais eficiente, por usar menos memria, que a API DOM do XmlDocument fornece. Apenas para mostrar uma comparao entre as duas tcnicas temos abaixo um trecho de um documento XML e em seguida o cdigo para a criao do documento usando a API DOM e o LINQ to XML:
arquivo XML <contatos> <contato> <nome>Macoratti</nome> <fone tipo="residencia">9986-5544</fone> <fone tipo="trabalho">9986-2585</fone> <endereco> <rua>rua Mirassol, 100</rua> <cidade>Brasilia</cidade> <estado>DF</estado> <postal>7860456</postal> </endereco>
</contato> </contatos>
Vamos criar um projeto do tipo Windows Application no VB 2008 Express para exibir o documento XML criado em um TextBox. Abra o VB 2008 Express e crie um novo projeto Windows Application e no formulrio padro form1.vb inclua dois botes de comando e uma caixa de texto - TextBox1 - com sua propriedade Multiline igual a True. a seguir inclua o cdigo abaixo no evento Click dos respectivos botes: Button1 - Cdigo para gerar o arquivo Button2 - Cdigo para gerar o XML XML usando a API DOM usando LINQ to XML
Dim doc As New XmlDocument() Dim nome As XmlElement = doc.CreateElement("nome") nome.InnerText = "Macoratti" Dim fone As XmlElement = doc.CreateElement("fone") fone.SetAttribute("tipo", "residencia") fone.InnerText = "9986-55-44" Dim fone1 As XmlElement = doc.CreateElement("fone") fone1.SetAttribute("tipo", "trabalho") fone1.InnerText = "9986-25-85" Dim rua As XmlElement = doc.CreateElement("rua") rua.InnerText = "Rua Mirassol , 100" Dim cidade As XmlElement = doc.CreateElement("cidade") cidade.InnerText = "Brasilia" Dim estado As XmlElement = doc.CreateElement("estado") estado.InnerText = "DF" Dim postal As XmlElement = doc.CreateElement("postal") postal.InnerText = "77860-456" Dim endereco As XmlElement = doc.CreateElement("endereco") endereco.AppendChild(rua) endereco.AppendChild(cidade) endereco.AppendChild(estado) endereco.AppendChild(postal) Dim contato As XmlElement = doc.CreateElement("contato") contato.AppendChild(nome) contato.AppendChild(fone) contato.AppendChild(fone1) contato.AppendChild(endereco) Dim contatos As XmlElement = doc.CreateElement("contatos") contatos.AppendChild(contato) doc.AppendChild(contatos) TextBox1.Text = doc.InnerXml
Dim contatos As New XElement("contatos", _ New XElement("contato", _ New XElement("nome", "Macoratti"), _ New XElement("fone", "9986-55-44", New XAttribute("tipo", "residencia")), _ New XElement("fone", "9986-85-25", New XAttribute("tipo", "trabalho")), _ New XElement("endereco", New XElement("rua", "Rua Mirassol, 100"), _ New XElement("cidade", "Brasila"), _ New XElement("estado", "DF"), _ New XElement("postal", "7786-456")))) TextBox1.Text = contatos.ToString
Perceba que no cdigo onde usamos DOM os ns, incluindo elementos e atributos, precisam ser criados no contexto de um documento XML:
Dim doc As New XmlDocument() Dim nome As XmlElement = doc.CreateElement("nome")
O conceito de documento XML fundamental no DOM e os ns XML so criados no contexto do documento XML, se voc desejar usar um elemento atravs de mltiplos documentos vai precisar importar os ns atravs do documento. O LINQ To XML simplifica essa abordagem.
XElement("nome")
No LINQ to XML voc pode criar elementos XML diretamente: Ex: Dim nome As New Vejamos a seguir a figura que mostra a hierarquia de classes do LINQ To XML
Embora o XElement esteja em um nvel inferior na hierarquia ele uma classe fundamental do LINQ To XML. As rvores XML so feitas de uma rvore de XElements. Os XAttributes so pares nome/valor associados a um XElement. Enquanto que os XDocument so criados somente se necessrio como para manipular um DTD ou uma instruo de processamento XML( XProcessingInstruction). Todos os outros XNodes podem somente ser ns abaixo de XElement ou de um XDocument se ele existir;
O nico XNode que pode possuir filhos e um XContainter : XDocument ou XElement. Um XDocument pode conter um XElement (a raiz), um XDeclaration , um XDocumentType ou um XProcessingInstruction. Um XElement pode conter outro XElement , um XProcessingInstruction e texto.
Descrio Atua como um container para a rvore XML e deve ser usado somente se nece XDocument documento com um arquivo XML. Permite criar elementos , modificar o contedo dos elementos (incluir, remov XElement filhos), modifica os atributos dos elementos , salvar como um arquivo XML. XAttribute Usado para criar um par nome/valor no interior de um elemento do arquivo X XName Representa um nome completo XML consistindo de um objeto XNamespace e d XComment Representa um comentrio XML. XDocumentType Representa um documento XML DTD - Document Type Definition. XProcesingInstructionRepresenta o processamento de uma instruo de um documento XML. XTest Representa um n Texto. XDeclaration Representa uma declarao XML. Vamos ver ento como esse tal de LINQ To XML funciona... Para poder usar os recursos do LINQ voc vai precisar possuir instalado o Visual Basic 2008 Express Edition: Se no tiver pegue aqui: Visual Basic 2008 Express Edition
A seguir temos duas maneiras distintas de obter o XML: 1- Usando somente a classe XElement podemos gerar diretamente o XML desejado. Inclua o cdigo abaixo no evento Click do boto de comando:
Dim xmlDoc As New XElement("clientes", _ New XElement("cliente", _ New XAttribute("codigo", "1"), _ New XElement("nome", "Macoratti"), _ New XElement("email", "[email protected]")), _ New XElement("cliente", _
New XAttribute("codigo", "2"), _ New XElement("nome", "Jessica"), _ New XElement("email", "[email protected]"))) txtXmlDoc.Text = xmlDoc.ToString
2- Usando o objeto Xdocument Neste caso vamos criar uma funo chamada CriarDocumentoXML() conforme abaixo:
Function criarDocumentoXML() As XDocument Return New XDocument( _ New XDeclaration("1.0", Nothing, Nothing), _ New XElement("clientes", _ New XElement("cliente", _ New XAttribute("codigo", "1"), _ New XElement("nome", "Macoratti"), _ New XElement("email", "[email protected]")), _ New XElement("cliente", _ New XAttribute("codigo", "2"), _ New XElement("nome", "Jessica"), _ New XElement("email", "[email protected]")))) End Function
Agora no evento Click do boto de comando inclua o cdigo:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim xmldoc = criarDocumentoXML() txtXmlDoc.Text = xmldoc.ToString End Sub
O resultado final seria o mesmo:
Podemos ainda criar o documento XML reescrevendo a funo CriarDocumentoXML usando o seguinte cdigo:
Function criarDocumentoXML() As XDocument Return <?xml version="1.0" encoding="UTF-16" standalone="yes"?> <clientes> <cliente codigo="1"> <nome>Macoratti</nome> <email>[email protected]</email> </cliente> <cliente codigo="2"> <nome>Jessica</nome> <email>[email protected]</email> </cliente> </clientes> End Function
O cdigo acima alm de mais legvel apresenta o xml agora sendo usado como um tipo do Visual Basic.
Realizando Consultas
Vamos realizar agora uma consulta no documento criado usando LINQ To XML. Inclua um novo controle TextBox com o nome txtXmlConsulta com Multiline=true e um boto de comando : Consulta XML, conforme o leiaute abaixo:
Agora inclua no evento Click do boto de comando Consulta XML o cdigo para obter o cliente de cdigo igual a 2:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim xmldoc = criarDocumentoXML() Dim clientes = From c In xmldoc...<cliente> _ Where c.@codigo = "2" For Each cliente In clientes txtXmlConsulta.Text = cliente.ToString Next End Sub
Para carregar um arquivo XML de outra fonte use o mtodo Load: Dim testeXML As XElement = XElement.Load("c:\teste\Macoratti.xml") Como vimos a API LINQ To XML se prope a efetuar o tratamento XML de uma maneira mais eficiente e com desempenho melhor. Aguarde em breve mais artigos sobre LINQ To XML... Pegue o projeto completo aqui : Referncias:
VB8_LINQ_XML1.zip
http://msdn2.microsoft.com/en-us/library/bb308960.aspx
C# VB.NET
1. static string arquivo = "C:\\documento.xml"; 1. Dim arquivo As String = "C:\\documento.xml" O namespace System.Xml.Linq contm todos os objetos necessrios para cria e manipular XML ,para criar um arquivo XML vamos utilizar a classe XElement .Todos com atributos e elementos sero criados com os mtodos SetAttributeValue e SetElementValue, para salvar o arquivo a classe disponibiliza o mtodo Save. Conforme o cdigo abaixo adicione o mtodo CriaXML a definio da classe Program e chame-o do mtodo Main.
C# VB.NET
1. static void CriaXML() 2. { 3. XElement documentoXml = new XElement("Clientes"); 4. XElement element = null; 5. 6. for (int i = 1; i <= 5; i++) 7. { 8. element = new XElement("Cliente", new XComment("Atributos do cliente " + i)); 9. 10. //Atributos 11. element.SetAttributeValue("Nome", String.Format("Nome {0}", i)); 12. element.SetAttributeValue("Endereco", String.Format("Endereo {0}", i)); 13. 14. //Elementos 15. element.SetElementValue("RG", String.Format("RG {0}", i)); 16. element.SetElementValue("CPF", String.Format("CPF {0}", i)); 17. 18. //Adiciona elemento ao elemento root 19. documentoXml.Add(element); 20. } 21. 22. documentoXml.Save(arquivo); 23. 24. Console.WriteLine(documentoXml); 25. } 1. Sub CriaXML() 2. Dim documentoXml As New XElement("Clientes") 3. Dim element As XElement = Nothing 4. 5. For I As Integer = 1 To 5 6. element = New XElement("Cliente", New XComment("Atributos do cliente " + I.ToStri ng())) 7. 8. 'Atributos 9. element.SetAttributeValue("Nome", String.Format("Nome {0}", I)) 10. element.SetAttributeValue("Endereco", String.Format("Endereo {0}", I)) 11. 12. 'Elementos 13. element.SetElementValue("RG", String.Format("RG {0}", I)) 14. element.SetElementValue("CPF", String.Format("CPF {0}", I)) 15. 16. 'Adiciona elemento ao elemento root 17. documentoXml.Add(element) 18. Next 19. 20. documentoXml.Save(arquivo) 21. 22. Console.WriteLine(documentoXml) 23. End Sub
Arquivo XML
1. <clientes> 2. <cliente nome="Nome 1" endereco="Endereo 1"> 3. <!--Atributos do cliente 1--> 4. <rg>RG 1</rg> 5. <cpf>CPF 1</cpf> 6. </cliente> 7. <cliente nome="Nome 2" endereco="Endereo 2"> 8. <!--Atributos do cliente 2--> 9. <rg>RG 2</rg> 10. <cpf>CPF 2</cpf> 11. </cliente> 12. <cliente nome="Nome 3" endereco="Endereo 3"> 13. <!--Atributos do cliente 3--> 14. <rg>RG 3</rg> 15. <cpf>CPF 3</cpf> 16. </cliente> 17. <cliente nome="Nome 4" endereco="Endereo 4"> 18. <!--Atributos do cliente 4--> 19. <rg>RG 4</rg> 20. <cpf>CPF 4</cpf> 21. </cliente> 22. <cliente nome="Nome 5" endereco="Endereo 5"> 23. <!--Atributos do cliente 5--> 24. <rg>RG 5</rg> 25. <cpf>CPF 5</cpf> 26. </cliente> 27. </clientes> Carregar arquivo Para carregar e selecionar valores utilizando Linq to XML podemos utilizar a classe XElement. Mtodo Load: carregar contedo XML de um arquivo ou da memrias a responsabilidade desse mtodo, em uma de suas sobrecargas podemos passar o caminho do arquivo XML , as outras sobrecargas recebe como parmetros um objeto TextReader ou XmlReader.Voc tambm pode definir opes partir do enum LoadOptions. O LoadOption possui quatro opes . None : todas as linhas desnecessrias,linhas em branco e linhas de informaes, do arquivo XML no sero carregadas. PreserveWhitespace: essa opo define que todas as linhas em branco do arquivo XML sero preservadas. SetBaseUri : essa opo define o preenchimento da propriedade BaseUri. SetLineInfo: essa opo habilita o preenchimento da das informaes de linha, essa informaes pode ser recuperadas atravs da interface IXmlLineInfo. Conforme cdigo abaixo adicione o mtodo CarregaSelecionaXml na definio da classe Program e chame-o do mtodo Main.
C#
VB.NET
1. static void CarregaSelecionaXml() 2. { 3. XElement xml = XElement.Load(arquivo, LoadOptions.SetBaseUri | LoadOptions.SetLine Info); 4. 5. //Mostra o caminho base. 6. Console.WriteLine("Caminho : {0}", xml.BaseUri); 7. 8. //Mostra informaes de linha 9. IXmlLineInfo lineInfo = xml as IXmlLineInfo; 10. Console.WriteLine("LineNumber : {0} e LinePosition: {1}", lineInfo.LineNumber, lineInf o.LinePosition); 11. 12. //Carrega todos os elementos dentro do elemento root 13. IEnumerable<xelement> enumerable = xml.Elements(); 14. 15. //Mostra todos os elementos dentro do elemento root 16. foreach (var item in enumerable) 17. Console.WriteLine(item); 18. 19. //Mostra todos os atributos nome do elento Cliente 20. foreach (var item in enumerable.Attributes("Nome")) 21. Console.WriteLine(item); 22. 23. //Mostra todos os elementos CPF dentro do elemento Cliente 24. foreach (var item in enumerable.Elements("CPF")) 25. Console.WriteLine(item); 26. } 27. </xelement> 1. Sub CarregaSelecionaXml() 2. Dim xml As XElement = XElement.Load(arquivo, LoadOptions.SetBaseUri Or LoadOptio ns.SetLineInfo) 3. 4. 'Mostra o caminho base. 5. Console.WriteLine("Caminho : {0}", xml.BaseUri) 6. 7. 'Mostra informaes de linha 8. Dim lineInfo As IXmlLineInfo = xml 9. 10. Console.WriteLine("LineNumber : {0} e LinePosition: {1}", lineInfo.LineNumber, lineInf o.LinePosition) 11. 12. 'Carrega todos os elementos dentro do elemento root 13. Dim Enumerable As IEnumerable(Of XElement) = xml.Elements() 14. 15. 'Mostra todos os elementos dentro do elemento root 16. For Each item In Enumerable
17. Console.WriteLine(item) 18. Next 19. 20. 'Mostra todos os atributos nome do elento Cliente 21. For Each item In Enumerable.Attributes("Nome") 22. Console.WriteLine(item) 23. Next 24. 25. 'Mostra todos os elementos CPF dentro do elemento Cliente 26. For Each item In Enumerable.Elements("CPF") 27. Console.WriteLine(item) 28. Next 29. End Sub Alterando valores Para isso utilizamos todo o poder do Linq para selecionar o atributo ou elemento que desejamos alterar. Conforme o cdigo abaixo adicione o mtodo AlterandoValores na definio da classe Program e chame-o do mtodo Main.
C# VB.NET
1. static void AlterandoValores() 2. { 3. XElement xml = XElement.Load(arquivo, LoadOptions.SetBaseUri | LoadOptions.SetLine Info); 4. IEnumerable<XElement> elements = xml.Elements(); 5. 6. //Seleciona e altera o elemento CPF aonde o valor seja igual a "CPF 1" 7. foreach (var item in elements.Elements("CPF").Where(e => e.Value == "CPF 1")) 8. item.Value = "123456789"; 9. 10. //Seleciona e altera o atributo Nome aonde o valor seja igual a "Nome 1" 11. foreach (var item in elements.Attributes("Nome").Where(e => e.Value == "Nome 1")) 12. item.Value = "Nome Alterado"; 13. 14. //Salva Alteraes 15. xml.Save(arquivo); 16. } 1. Sub AlterandoValores() 2. Dim xml As XElement = XElement.Load(arquivo, LoadOptions.SetBaseUri Or LoadOptio ns.SetLineInfo) 3. 4. Dim elements As IEnumerable(Of XElement) = xml.Elements() 5. 6. 'Seleciona e altera o elemento CPF aonde o valor seja igual a "CPF 1"
7. For Each item In elements.Elements("CPF").Where(Function(e) e.Value = "CPF 1") 8. item.Value = "123456789" 9. Next 10. 11. 'Seleciona e altera o atributo Nome aonde o valor seja igual a "Nome 1" 12. For Each item In elements.Attributes("Nome").Where(Function(e) e.Value = "Nome 1") 13. item.Value = "Nome Alterado" 14. Next 15. 16. 'Salva Alteraes 17. xml.Save(arquivo) 18. End Sub Excluindo Valores O cdigo abaixo demonstra como excluir um elemento do arquivo XML, esse exemplo retira o elemento cliente aonde o atributo nome seja igual a "Nome 2", e para isso vamos utilizar mais uma vez o poder do Linq. Conforme o cdigo abaixo adicione o mtodo ExcluindoValores na definio da classe Program e chame-o do mtodo Main.
C# VB.NET
1. static void ExcluindoValores() 2. { 3. XElement xml = XElement.Load(arquivo, LoadOptions.SetBaseUri | LoadOptions.SetLine Info); 4. IEnumerable<XElement> elements = xml.Elements(); 5. 6. //Exclui elemento Cliente aonde o Atributo Nome seja igual a "Nome 2" 7. elements.AncestorsAndSelf("Cliente").Where(e => e.Attribute("Nome").Value == "Nome 2").Remove(); 8. 9. //Salva Alteraes 10. xml.Save(arquivo); 11. } 1. Sub ExcluindoValores() 2. Dim xml As XElement = XElement.Load(arquivo, LoadOptions.SetBaseUri Or LoadOptio ns.SetLineInfo) 3. 4. Dim elements As IEnumerable(Of XElement) = xml.Elements() 5. 6. 'Exclui elemento Cliente aonde o Atributo Nome seja igual a "Nome 2" 7. elements.AncestorsAndSelf("Cliente").Where(Function(e) e.Attribute("Nome").Value = " Nome 2").Remove() 8. 9. 'Salva Alteraes
10. xml.Save(arquivo) 11. End Sub Concluso Com esse simples exemplo da para se ter idia do que o Linq to XML e capaz, a criao de manipulao de arquivos XML ficou muito mais fcil, ficou claro que o objeto XElement possui todas as funcionalidades necessrias para manipulao de arquivos XML, claro o Linq to XML no se define a um nico objeto mais ele com certeza da conta do recado. Referncias http://msdn.microsoft.com/en-us/library/bb308960.aspx