Reading XML in C#

Asked

Viewed 4,863 times

3

I know there is a lot of Post on how to read a file XML, but I didn’t find any that present the XML with the same structure I have.

I have the following Code.

private void LeituraXML()
{

    //Criando objeto xml para abrir o arquivo de configuração

    XmlDocument doc = new XmlDocument();
    //Informando o caminho onde esta salvo o arquivo xml

    string cadastro = @"C:\Users\Dell\Documents\Tipo_Documentos.xml";
    doc.Load(cadastro);
    XmlNodeList nodelist = doc.SelectNodes("data");

    foreach (XmlNode node in nodelist)
    {
       string teste1 = node.SelectSingleNode("tipo").InnerText;
       string teste2 = node.SelectSingleNode("metadata").InnerText;
    }
}

and with the XML

<service>
    <name>TiposDocumentaisEMetadados</name>
</service>
<message>
    <type>success</type>
<value/>
</message>
<data>
    <tipo codigo="7" name="Comprovante de Endereço">
      <metadata name="numero_documento" required="false" type="string" max_length="255"/>
      <metadata name="protocolo_processo" required="false" type="string" max_length="255"/>
      <metadata name="assunto" required="false" type="string" max_length="800"/>
      <metadata name="interessado" required="false" type="string" max_length="255"/>
      <metadata name="observacao" required="false" type="string" max_length="255"/>
      <metadata name="data_documento" required="true" type="date_time"/>
      <metadata name="login_autor" required="true" type="string" max_length="50"/>
    </tipo>
</data>

I need to add in variables the code and the name of Tags <tipo> and the tag <metadata> I just need the name?

  • 1

    your xml is just that?

2 answers

3

The archive is badly formatted, needs to have a tag root and so I arranged to answer the question by adding the element root for reading.

Modified file:

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <service>
    <name>TiposDocumentaisEMetadados</name>
  </service>
  <message>
    <type>success</type>
    <value/>
  </message>
  <data>
    <tipo codigo="7" name="Comprovante de Endereço">
      <metadata name="numero_documento" required="false" type="string" max_length="255"/>
      <metadata name="protocolo_processo" required="false" type="string" max_length="255"/>
      <metadata name="assunto" required="false" type="string" max_length="800"/>
      <metadata name="interessado" required="false" type="string" max_length="255"/>
      <metadata name="observacao" required="false" type="string" max_length="255"/>
      <metadata name="data_documento" required="true" type="date_time"/>
      <metadata name="login_autor" required="true" type="string" max_length="50"/>
    </tipo>
  </data>
</root>

Code for reading

In the Selectnodes needs to pass the complete path that in the current case begins from the root and goes up to tipo and then the list of metadata:

Example of the paths:

//root//data//tipo

//root//data//tipo//metadata

and then take the values of their atributos, example:

private static void LeituraXML()
{           

    XmlDocument doc = new XmlDocument();
    string cadastro = @"./base.xml";
    doc.Load(cadastro);
    XmlNode nodeListTipo = doc.SelectNodes("//root//data//tipo").Item(0);
    XmlNodeList nodeListMetadata = doc.SelectNodes("//root//data//tipo//metadata");

    String codigoTipo = nodeListTipo.Attributes["codigo"].Value;
    string nameTipo = nodeListTipo.Attributes["name"].Value;           

    foreach (XmlNode node in nodeListMetadata)
    {
        string nameMetadata = node.Attributes["name"].Value;
        string requiredMetadata = node.Attributes["required"].Value;
        string typeMetadata = node.Attributes["type"].Value;
        string max_lengthMetadata = node.Attributes["max_length"].Value;                

        // aqui os dados se repetem e podem ser colocados
        // em uma coleção de uma determinada classe
        // exemplo List<Metadata> ex ....
    }
}

Observing: note the 3 comments, within the repeating structure for, the metadata are several, so depending on your rule you may need to use a list of values (collection).

Reading

References

1


You can read and write the data using the class Xmlserializer, for this, you only need to have a class that represents the content of your XML, I will use as a basis the part of XML that you posted.

Example class based on your XML:

public class Config
{
    public Service service { get; set; }
    public Message message{ get; set; }
    public Data data { get; set; }
}

public class Service
{
    public string name { get; set; }
}

public class Message
{
    public string type { get; set; }
    public string value { get; set; }
}

public class Data
{
    public TipoData tipo { get; set; }
}

public class TipoData
{
    public int codigo { get; set; }
    public string name { get; set; }
    public List<MetaData> metadata { get; set; }
}

public class MetaData
{
    public string name { get; set; }
    public bool required { get; set; }
    public string type { get; set; }
    public int max_length { get; set; }
}

To serialize your object and save in XML use:

var serializer = new XmlSerializer(typeof(Config));
var localArquivo = "C:/arquivo.xml";
var xmlNamespaces = new XmlSerializerNamespaces();

using (var textWriter = new StreamWriter(localArquivo))
{
    serializer.Serialize(textWriter, conteudo, xmlNamespaces);
}

And to deserialize XML and use it in your code:

var serializer = new XmlSerializer(typeof(Config));
var configuracao = new Config();
var localArquivo = "C:/arquivo.xml";

using (var textReader = new StreamReader(localDoArquivo))
{
    configuracao = (Config)serializer.Deserialize(textReader);
}

You will use the following usings:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.