Como é que leio e analiso um ficheiro XML em C#?
como é que leio e analiso um ficheiro XML em C#?
11 answers
XmlDocument para ler um XML do texto ou do ficheiro.
XmlDocument doc = new XmlDocument();
doc.Load("c:\\temp.xml");
Ou
doc.LoadXml("<xml>something</xml>");
Depois encontra um nó por baixo dele, ou seja, assim
XmlNode node = doc.DocumentElement.SelectSingleNode("/book/title");
Ou
foreach(XmlNode node in doc.DocumentElement.ChildNodes){
string text = node.InnerText; //or loop through its children as well
}
Então leia o texto dentro desse nó assim
string text = node.InnerText;
Ou ler um atributo
string attr = node.Attributes["theattributename"]?.InnerText
Verifique sempre se o atributo é nulo nos atributos["alguma coisa"], uma vez que será nulo se o atributo não existir.
LINQ para XML exemplo:
// Loading from a file, you can also load from a stream
var xml = XDocument.Load(@"C:\contacts.xml");
// Query the data and write out a subset of contacts
var query = from c in xml.Root.Descendants("contact")
where (int)c.Attribute("id") < 4
select c.Element("firstName").Value + " " +
c.Element("lastName").Value;
foreach (string name in query)
{
Console.WriteLine("Contact's Full Name: {0}", name);
}
Referência: LINQ para XML no MSDN
Aqui está uma aplicação que escrevi para ler sitemaps xml:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using System.Xml;
namespace SiteMapReader
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please Enter the Location of the file");
// get the location we want to get the sitemaps from
string dirLoc = Console.ReadLine();
// get all the sitemaps
string[] sitemaps = Directory.GetFiles(dirLoc);
StreamWriter sw = new StreamWriter(Application.StartupPath + @"\locs.txt", true);
// loop through each file
foreach (string sitemap in sitemaps)
{
try
{
// new xdoc instance
XmlDocument xDoc = new XmlDocument();
//load up the xml from the location
xDoc.Load(sitemap);
// cycle through each child noed
foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
{
// first node is the url ... have to go to nexted loc node
foreach (XmlNode locNode in node)
{
// thereare a couple child nodes here so only take data from node named loc
if (locNode.Name == "loc")
{
// get the content of the loc node
string loc = locNode.InnerText;
// write it to the console so you can see its working
Console.WriteLine(loc + Environment.NewLine);
// write it to the file
sw.Write(loc + Environment.NewLine);
}
}
}
}
catch { }
}
Console.WriteLine("All Done :-)");
Console.ReadLine();
}
static void readSitemap()
{
}
}
}
Código na pasta http://pastebin.com/yK7cSNeY
Há muitos caminhos, alguns:
- XmlSerializer. usar uma classe com o esquema de destino você deseja ler-use o Xmlserializador para obter os dados em um Xml carregado em um exemplo da classe.
- LINQ 2 xml
- XmlTextReader.
- XmlDocument
- XPathDocument (acesso apenas para leitura)
Você poderia usar um conjunto de dados para ler strings XML.
var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);
Afixar isto para bem da informação.
Você pode:
- Utilizar A classe XmlSerializer
- utilizar XmlDocument class
Existem exemplos nas páginas msdn fornecidas
Também, VB.NET tem um suporte de processamento xml muito melhor através do compilador do que C#. Se você tem a opção e o desejo, confira.
Confiraa classe XmlTextReader , por exemplo.
public void ReadXmlFile()
{
string path = HttpContext.Current.Server.MapPath("~/App_Data"); // Finds the location of App_Data on server.
XmlTextReader reader = new XmlTextReader(System.IO.Path.Combine(path, "XMLFile7.xml")); //Combines the location of App_Data and the file name
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
columnNames.Add(reader.Value);
break;
case XmlNodeType.EndElement:
break;
}
}
}
Você pode evitar a primeira declaração e apenas especificar o nome do caminho no construtor do XmlTextReader.
Eu escrevi este comentário, porque eu vejo um lof de exemplos com XDocument. XDocument não é bom para documentos grandes, ou quando você só quer verificar se lá o conteúdo é XML válido. Se você deseja verificar se o XML em si faz sentido, então você precisa de esquema.
Também rejeitei a resposta sugerida, porque acredito que precisa da informação acima dentro de si. Imagine que eu preciso verificar se 200M de XML, 10 vezes por hora, é válido XML. O XDocument irá desperdicem um monte de recursos.Prasanna venkatesh também afirma que você poderia tentar preencher o texto para um conjunto de dados, que indicará XML válido também.
Se quiser obter um determinado valor de um ficheiro XML
XmlDocument _LocalInfo_Xml = new XmlDocument();
_LocalInfo_Xml.Load(fileName);
XmlElement _XmlElement;
_XmlElement = _LocalInfo_Xml.GetElementsByTagName("UserId")[0] as XmlElement;
string Value = _XmlElement.InnerText;