Reading XML in C #

3

I know there's a lot of Post about how to read a XML file, but I do not find any that has 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 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 the code and name of TAGs <tipo> to the variables and the% tag I just need <metadata> ?

    
asked by anonymous 29.08.2017 / 22:21

2 answers

1

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

Class example 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 to 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 the 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;
    
29.08.2017 / 23:29
3

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

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 SelectNodes you need to pass the full path that in the case current starts from root and goes to tipo and then the list of metadata :

Example paths:

  

//root//data//tipo

     

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

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

Note: Note the 3 comments, within the% re_% structure,%% are several, so depending on your rule you can you need to use a list of values (collection).

Reading

References

29.08.2017 / 22:53