¿Cómo se analizan los archivos XML? [cerrado]


¿Existe un método sencillo para analizar archivos XML en C#? Si es así, ¿qué?

 492
Author: John Saunders, 2008-09-11

12 answers

Usaría LINQ a XML si está en.NET 3.5 o superior.

 228
Author: Jon Galloway,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-23 15:45:33

Es muy simple. Sé que estos son métodos estándar, pero puede crear su propia biblioteca para lidiar con eso mucho mejor.

Aquí hay algunos ejemplos:

XmlDocument xmlDoc= new XmlDocument(); // Create an XML document object
xmlDoc.Load("yourXMLFile.xml"); // Load the XML document from the specified file

// Get elements
XmlNodeList girlAddress = xmlDoc.GetElementsByTagName("gAddress");
XmlNodeList girlAge = xmlDoc.GetElementsByTagName("gAge"); 
XmlNodeList girlCellPhoneNumber = xmlDoc.GetElementsByTagName("gPhone");

// Display the results
Console.WriteLine("Address: " + girlAddress[0].InnerText);
Console.WriteLine("Age: " + girlAge[0].InnerText);
Console.WriteLine("Phone Number: " + girlCellPhoneNumber[0].InnerText);

También, hay algunos otros métodos para trabajar con. Por ejemplo, aquí. Y creo que no hay un mejor método para hacer esto; siempre tienes que elegir por ti mismo, lo que es más adecuado para ti.

 288
Author: Lukas Šalkauskas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-15 04:15:20

Utilice un buen Esquema XSDpara crear un conjunto de clases con xsd.exe y utilizar un XmlSerializer para crear un árbol de objetos a partir de su XML y viceversa. Si tiene pocas restricciones en su modelo, incluso podría intentar crear una asignación directa entre las clases del modelo y el XML con los atributos Xml*.

Existe un artículo introductorio sobre la serialización XML en MSDN.

Consejo de rendimiento: Construir un XmlSerializer es caro. Mantener una referencia a su instancia XmlSerializer si tiene la intención de analizar/escribir varios archivos XML.

 44
Author: David Schmitt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-16 01:22:55

Si está procesando una gran cantidad de datos (muchos megabytes), entonces desea usar XmlReader para analizar el XML en streaming.

Cualquier otra cosa (XPathNavigator, XElement, XmlDocument e incluso XmlSerializer si mantiene el gráfico de objetos generado completo) resultará en un alto uso de memoria y también un tiempo de carga muy lento.

Por supuesto, si necesita todos los datos en la memoria de todos modos, entonces puede que no tenga muchas opciones.

 22
Author: Simon Steele,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:49

Uso XmlTextReader, XmlReader, XmlNodeReader y el System.Xml.XPath espacio de nombres. Y (XPathNavigator, XPathDocument, XPathExpression, XPathnodeIterator).

Normalmente XPath facilita la lectura de XML, que es lo que podrías estar buscando.

 15
Author: Vinko Vrsalovic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-16 01:21:32

Si usted está utilizando .NET 2.0, try XmlReader y sus subclases XmlTextReader, y XmlValidatingReader. Proporcionan un rápido, ligero (uso de memoria, etc.), forward-only forma de analizar un archivo XML.

Si usted necesita XPath capacidades, pruebe el XPathNavigator. Si necesita el documento completo en memoria, intente XmlDocument.

 6
Author: Ash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-16 01:22:24

No estoy seguro de si existe la "mejor práctica para analizar XML". Existen numerosas tecnologías adecuadas para diferentes situaciones. Qué manera de usar depende del escenario concreto.

Con LINQ to XML, XmlReader, XPathNavigator o incluso expresiones regulares. Si usted elabora sus necesidades, puedo tratar de dar algunas sugerencias.

 5
Author: aku,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-16 01:21:51

Recientemente se me ha pedido que trabaje en una aplicación que involucraba el análisis de un documento XML y estoy de acuerdo con Jon Galloway en que el enfoque basado en LINQ a XML es, en mi opinión, el mejor. Sin embargo, tuve que cavar un poco para encontrar ejemplos utilizables,así que sin más preámbulos, aquí hay algunos!

Cualquier comentario bienvenido ya que este código funciona, pero puede no ser perfecto y me gustaría aprender más sobre el análisis XML para este proyecto!

public void ParseXML(string filePath)  
{  
    // create document instance using XML file path
    XDocument doc = XDocument.Load(filePath);

    // get the namespace to that within of the XML (xmlns="...")
    XElement root = doc.Root;
    XNamespace ns = root.GetDefaultNamespace();

    // obtain a list of elements with specific tag
    IEnumerable<XElement> elements = from c in doc.Descendants(ns + "exampleTagName") select c;

    // obtain a single element with specific tag (first instance), useful if only expecting one instance of the tag in the target doc
    XElement element = (from c in doc.Descendants(ns + "exampleTagName" select c).First();

    // obtain an element from within an element, same as from doc
    XElement embeddedElement = (from c in element.Descendants(ns + "exampleEmbeddedTagName" select c).First();

    // obtain an attribute from an element
    XAttribute attribute = element.Attribute("exampleAttributeName");
}

Con estas funciones fui capaz de analizar cualquier elemento y cualquier atributo de un archivo XML no hay problema en absoluto!

 5
Author: PJRobot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-23 11:09:28

Puede analizar el XML usando esta biblioteca System.Xml.Linq. A continuación se muestra el código de ejemplo que utilicé para analizar un archivo XML

public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
    string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);

    XDocument xDoc = XDocument.Load(path);

    XElement xElement = XElement.Parse(xDoc.ToString());


    List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
    {
        Code = Convert.ToString(d.Element("CategoryCode").Value),
        CategoryPath = d.Element("CategoryPath").Value,
        Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
        SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
    }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();

    CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);

    return catSubCatList;
}
 2
Author: Tapan kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-19 19:05:59

Además, puede usar el selector XPath de la siguiente manera (forma fácil de seleccionar nodos específicos):

XmlDocument doc = new XmlDocument();
doc.Load("test.xml");

var found = doc.DocumentElement.SelectNodes("//book[@title='Barry Poter']"); // select all Book elements in whole dom, with attribute title with value 'Barry Poter'

// Retrieve your data here or change XML here:
foreach (XmlNode book in nodeList)
{
  book.InnerText="The story began as it was...";
}

Console.WriteLine("Display XML:");
doc.Save(Console.Out);

La documentación

 2
Author: Joel Harkes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-17 12:19:38

Puede usar ExtendedXmlSerializer para serializar y deserializar.

Instalación Puede instalar ExtendedXmlSerializer desde nuget o ejecutar el siguiente comando:

Install-Package ExtendedXmlSerializer

Serialización:

ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
var obj = new Message();
var xml = serializer.Serialize(obj);

Deserialización

var obj2 = serializer.Deserialize<Message>(xml);

El serializador XML estándar en. NET es muy limitado.

  • No admite serialización de clase con referencia circular o clase con interfaz propiedad,
  • No soporta Diccionarios,
  • No hay ningún mecanismo para leer la versión antigua de XML,
  • Si desea crear un serializador personalizado, su clase debe heredar de IXmlSerializable. Esto significa que su clase no será una clase POCO,
  • No es compatible con el CoI.

ExtendedXmlSerializer puede hacer esto y mucho más.

ExtendedXmlSerializer apoyo .NET 4.5 o superior y .NET Core. Puede integrar con WebAPI y AspCore.

 0
Author: Wojtpl2,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 14:26:33

Puede usar XmlDocument y para manipular o recuperar datos de atributos puede Linq a clases XML.

 0
Author: shaishav shukla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-16 12:27:26