2.0 Crear un XmlNamespaceManager basandose en un fichero XML

2028 vistas

Podemos ver cómo [iurl=91&all=0&fs=1229#1230]leer un fichero XML con las clases de XPath[/iurl]. En el caso de tener el fichero XML namespaces, hemos usado la clase XmlNamespaceManager para gestionar estos namespaces. El único defecto es que alimentamos manualmente estos datos. Veamos cómo crear este XmlNamespaceManager de forma automática.

Fichero XML usado para el ejemplo:



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.Collections.Generic;
  2. using System.Xml;
  3. using System.Xml.XPath;
  4. ...
  5. private XmlNamespaceManager GetXmlNamespaceManager(XPathNavigator
  6. nav)
  7. {           
  8.     XmlNamespaceManager mgr = null;
  9.  
  10.     nav.MoveToFirstChild();
  11.     foreach (KeyValuePair<string, string> keyPair in
  12.         nav.GetNamespacesInScope(XmlNamespaceScope.Local))
  13.     {
  14.         if (mgr == null)
  15.         { mgr = new XmlNamespaceManager(nav.NameTable);}
  16.         mgr.AddNamespace(keyPair.Key, keyPair.Value);
  17.     }
  18.     nav.MoveToRoot();
  19.  
  20.     return mgr;
  21. }
  22.  
  23. private void TraiteXml(string fileName)
  24. {
  25.   XPathDocument doc = new XPathDocument(fileName);
  26.   XPathNavigator nav = doc.CreateNavigator();
  27.   XmlNamespaceManager mgr = GetXmlNamespaceManager(nav);           
  28.   if (mgr != null)
  29.   {
  30.     XPathNodeIterator iter = nav.Select
  31. ("rd:Recordbook/rd:Records/rd:Record", mgr);
  32.         while (iter.MoveNext())
  33.         {
  34.             string firstValue = iter.Current.SelectSingleNode
  35.                 ("rd:FirstValue", mgr).Value;
  36.             string secondValue = iter.Current.SelectSingleNode
  37.                 ("rd:SecondValue", mgr).Value;
  38.         }
  39.     }
  40. }