xdocument name example c# .net linq linq-to-xml

c# - name - Cómo obtener el nodo XML de XDocument



xdocument c# example (2)

La operación .Elements devuelve una LISTA de XElements, pero lo que realmente desea es un elemento SINGLE. Agrega esto:

XElement Contacts = (from xml2 in XMLDoc.Elements("Contacts").Elements("Node") where xml2.Element("ID").Value == variable select xml2).FirstOrDefault();

De esta forma, le dice a LINQ que le proporcione el primero (o NULO, si no hay ninguno) de esa LISTA de elementos XE que está seleccionando.

Bagazo

¿Cómo obtener un elemento XML de XDocument usando LINQ?

Supongamos que tengo un XDocument Named XMLDoc que se muestra a continuación:

<Contacts> <Node> <ID>123</ID> <Name>ABC</Name> </Node> <Node> <ID>124</ID> <Name>DEF</Name> </Node> </Contacts> XElement Contacts = from xml2 in XMLDoc.Elements("Contacts").Elements("Node") where xml2.Element("ID").Value == variable select xml2;

Pero recibo el error "Referencia de objeto NO es establecer ....."

¿Cómo obtener un Nodo particular de un archivo XML usando LINQ? Y quiero actualizar algunos valores en ese nodo?

Como es posible ????

Gracias por adelantado.........


Respuesta a una pregunta adicional publicada por OP.

test.xml:

<?xml version="1.0" encoding="utf-8"?> <Contacts> <Node> <ID>123</ID> <Name>ABC</Name> </Node> <Node> <ID>124</ID> <Name>DEF</Name> </Node> </Contacts>

Seleccione un solo nodo:

XDocument XMLDoc = XDocument.Load("test.xml"); string id = "123"; // id to be selected XElement Contact = (from xml2 in XMLDoc.Descendants("Node") where xml2.Element("ID").Value == id select xml2).FirstOrDefault(); Console.WriteLine(Contact.ToString());

Eliminar un solo nodo:

XDocument XMLDoc = XDocument.Load("test.xml"); string id = "123"; var Contact = (from xml2 in XMLDoc.Descendants("Node") where xml2.Element("ID").Value == id select xml2).FirstOrDefault(); Contact.Remove(); XMLDoc.Save("test.xml");

Agregar nuevo nodo:

XDocument XMLDoc = XDocument.Load("test.xml"); XElement newNode = new XElement("Node", new XElement("ID", "500"), new XElement("Name", "Whatever") ); XMLDoc.Element("Contacts").Add(newNode); XMLDoc.Save("test.xml");