Leer un fichero XML con las clases del namespace System.Xml.Xpath

2192 vistas

Veamos un ejemplo básico de lectura de un fichero XML, pero sin servirse de la clase XmlDocument, sino de las clases del namespace System.Xml.Xpath. Podemos diferenciar dos casos, los fichero XML base y los que tienen un namespace.

1.- Fichero XML básico



xml
  1. <Recordbook>
  2.   <Records>
  3.     <Record>
  4.       <FirstValue>10</FirstValue>
  5.       <SecondValue>51</SecondValue>
  6.     </Record>
  7.     <Record>
  8.       <FirstValue>25</FirstValue>
  9.       <SecondValue>38</SecondValue>
  10.     </Record>
  11.   </Records>
  12. </Recordbook>



Su implementación:



csharp
  1. using System.Xml.XPath;
  2. ...
  3. private void TraiteXml()
  4. {
  5.     XPathDocument doc = new XPathDocument(fileName);
  6.     XPathNavigator nav = doc.CreateNavigator();
  7.     // recuperamos un XPathNodeIterator
  8.     XPathNodeIterator iter = nav.Select("Recordbook/Records/Record");
  9.     // Para cada Record
  10.     while (iter.MoveNext())
  11.     {
  12.         // recuperamos la info FirstValue
  13.         string firstValue=iter.Current.SelectSingleNode("FirstValue").Value;
  14.         // recuperamos la info SecondValue
  15.         string secondValue = iter.Current.SelectSingleNode
  16. ("SecondValue").Value; 
  17.     }
  18. }



2.- Fichero XML con un namespace



xml
  1. <rd:Recordbook xmlns:rd="http://myexemple/myschema/record">
  2.   <rd:Records>
  3.     <rd:Record>
  4.       <rd:FirstValue>10</rd:FirstValue>
  5.       <rd:SecondValue>51</rd:SecondValue>
  6.     </rd:Record>
  7.     <rd:Record>
  8.       <rd:FirstValue>25</rd:FirstValue>
  9.       <rd:SecondValue>38</rd:SecondValue>
  10.     </rd:Record>
  11.   </rd:Records>
  12. </rd:Recordbook>



Su implementación:



csharp
  1. using System.Xml;
  2. using System.Xml.XPath;
  3. //...
  4. private void TraiteXml()
  5. {
  6.     XPathDocument doc = new XPathDocument(fileName);
  7.     XPathNavigator nav = doc.CreateNavigator();
  8.     // gestión de los spacenames
  9.     XmlNamespaceManager mgr = new XmlNamespaceManager
  10. (nav.NameTable);
  11.     mgr.AddNamespace("rd", http://myexemple/myschema/record);
  12.     // recuperamos un XPathNodeIterator
  13.     XPathNodeIterator iter = nav.Select
  14. ("rd:Recordbook/rd:Records/rd:Record", mgr);
  15.     // para cada Record
  16.     while (iter.MoveNext())
  17.     {
  18.         // recuperamos la info FirstValue
  19.         string firstValue = iter.Current.SelectSingleNode("rd:FirstValue",
  20. mgr).Value;
  21.         // recuperamos la info SecondValue
  22.         string secondValue = iter.Current.SelectSingleNode
  23. ("rd:SecondValue", mgr).Value;
  24.     }
  25. }



Nota:



csharp
  1. nav.Select("Recordbook/Records/Record");



y



csharp
  1. nav.Select("Recordbook/Records/record");



no representan la misma cosa