get node value from string xml - c#

I have this string XML
string innerXml = #"<detail><WCFFaultExcepcion xmlns=""http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId><Message>Índice fuera de los límites de la matriz.</Message></WCFFaultExcepcion></detail>";
This is the stringXML
<detail>
<WCFFaultExcepcion xmlns="http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId>
<Message>Índice fuera de los límites de la matriz.</Message>
</WCFFaultExcepcion>
</detail>
What I want is to get the value of the detail Tag, I’m trying with this example but all return null o cero count, could you help me?
private static void Example()
{
string innerXml = #"<detail><WCFFaultExcepcion xmlns=""http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId><Message>Índice fuera de los límites de la matriz.</Message></WCFFaultExcepcion></detail>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(innerXml);
XmlNode node = (XmlNode)doc.DocumentElement;
XmlNode optionalNode = node.SelectSingleNode("/detail/WCFFaultExcepcion");
XmlNode optionalNode1 = node.SelectSingleNode("detail/WCFFaultExcepcion");
XmlNode optionalNode2 = node.SelectSingleNode("/detail/WCFFaultExcepcion/ErrorId");
XmlNode optionalNode3 = node.SelectSingleNode("detail/WCFFaultExcepcion/ErrorId");
XmlElement optional = doc.SelectSingleNode(#"/detail/WCFFaultExcepcion/ErrorId") as XmlElement;
XmlElement optiona2 = doc.SelectSingleNode(#"detail/WCFFaultExcepcion/ErrorId") as XmlElement;
XmlNode xNode = doc.DocumentElement.SelectNodes("ErrorId")[0];
XmlNodeList xnList = doc.SelectNodes("/detail/WCFFaultExcepcion");
XmlNodeList xnList1 = doc.SelectNodes("detail/WCFFaultExcepcion");
XmlNodeList xnList2 = doc.SelectNodes("/detail/WCFFaultExcepcion/ErrorId");
XmlNodeList xnList3 = doc.SelectNodes("detail/WCFFaultExcepcion/ErrorId");
}

I think this might be the solution for you:
XmlDocument doc = new XmlDocument();
doc.LoadXml(innerXml);
XmlNodeList ErrorIdTags = doc.GetElementsByTagName("ErrorId");
if(ErrorIdTags.Count <= 1)
{
// The tag could not be fond
}
else
{
// The tag could be found!
string ErrorId = ErrorIdTags[0].InnerText;
}

Try using Linq to Xml (http://msdn.microsoft.com/en-us/library/bb387098%28v=VS.100%29.aspx) - the code will be really elegant.

The first try XmlNode node = (XmlNode)doc.DocumentElement; should work and should contain children. Try XmlNode firstChildNode = node.FirstChild; ... this will get you the first child, and won't be empty/null.
But when using xpath, you will get into problems because of the defined namespace. You will have to create a new namespace in doc, and assign http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades a shorthand (eg. sh ) ... then later in your xpath you can like go doc.SelectSingleNode(#"/detail/sh:WCFFaultExcepcion/sh:ErrorId")

Related

How to retrieve attribute from XML file in C#

I'm complete rookie I need to retrieve the value of last id in XML file here is
You can also use XPath within the Xml DOM like this :
string title;
XmlDocument xml = new XmlDocument();
xml.Load("~/purchases.xml");
// Or any other method to load your xml data in the XmlDocument.
// For example if your xml data are in a string, use the LoadXml method.
XmlElement elt = xml.SelectSingleNode("//SubMenu[#id='1']") as XmlElement;
if(elt!=null)
{
name=elt.GetAttribute("title");
}
Reference
As Jon suggested, you can use Linq To XML here.
XElement books = XElement.Load(filePath);
var lastId = books.Descendants("book").Select(x=>Int32.Parse(x.Attribute("ID").Value)).Last();
This will give you the last ID in the current list.You can now create your new Node
books.Add(new XElement("book",new XAttribute("ID",(lastId+1).ToString()),
new XAttribute("title","New Title"),
new XAttribute("price","1234")));
books.Save(filePath);
XmlDocument doc = new XmlDocument();
doc.Load("Yourxmlfilepath.xml");
//Display all the book titles.
XmlNodeList xNodeList = doc.SelectNodes("/bookstore/book");
foreach (XmlNode xNode in xNodeList)
{
var employeeName = xNode.OuterXml;
XmlDocument docnew = new XmlDocument();
docnew.LoadXml(employeeName);
foreach (XmlElement report in docnew.SelectNodes("book"))
{
string ID = report.GetAttribute("ID");
string title = report.GetAttribute("title");
string quantity = report.GetAttribute("quantity");
string price = report.GetAttribute("price");
}
}

Read Array in XML in C#

I'm trying to read arrays in an XML, but my code does not return results
XML :
<ArrayOfProductoModel
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/WebApi.Models">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>
Code :
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(content);
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
As I can read the array?
The problem is the imported namespace. You can ignore the namespace as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("*[local-name()='ProductoModel']");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("*[local-name()='descripcion']").InnerText);
}
Alternatively you can use an XmlNamespaceManager as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("MYNS", "http://schemas.datacontract.org/2004/07/WebApi.Models");
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("MYNS:ProductoModel", manager);
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("MYNS:descripcion", manager).InnerText);
}
Another solution is to use Linq to XML
var xml = #"<ArrayOfProductoModel
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""
xmlns=""http://schemas.datacontract.org/2004/07/WebApi.Models"">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>";
var xDoc = XDocument.Parse(xml);
var ns = xDoc.Root.Name.Namespace;
var nodelist = xDoc.Element(ns + "ArrayOfProductoModel").Elements(ns + "ProductoModel");
foreach (var node in nodelist)
{
MessageBox.Show(node.Element(ns + "descripcion").Value);
}
Don't forget to put namespace in front of local name.
At first, I think problem in
xDoc.LoadXml(content);
You try:
xDoc.Load(filePathXml);
Second, I think problem in
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
You try:
XmlNode rootNode = doc.SelectSingleNode(#"/ArrayOfProductoModel");
var listProductModel = rootNode.SelectNodes(#"ProductoModel");
foreach (XmlNode node in listProductModel)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}

How to add nodes with the same name in a loop?

I'm trying to create the following XML file:
<Clientes>
<Cliente>
<Name>sfsdfsd</Name>
<Phone>
</Phone>
<Matriculas>
<Matricula>
<Nr>567856786</Nr>
<Marca>86786</Marca>
<Modelo>8678678</Modelo>
</Matricula>
<Matricula>
<Nr>u56u5u</Nr>
<Marca>4564b5</Marca>
<Modelo>b456b</Modelo>
</Matricula>
</Matriculas>
</Cliente>
</Clientes>
I have several clientes stored in a List and each of them may have more then one Matricula, stored in a List
i have the following code:
foreach (Cliente c in cli)
{
XmlNode xCliente = xDoc.CreateElement("Cliente");
XmlNode xName = xDoc.CreateElement("Name");
XmlNode xPhone = xDoc.CreateElement("Phone");
XmlNode xMatriculas = xDoc.CreateElement("Matriculas");
XmlNode xMatricula = xDoc.CreateElement("Matricula");
XmlNode xNr = xDoc.CreateElement("Nr");
XmlNode xMarca = xDoc.CreateElement("Marca");
XmlNode xModelo = xDoc.CreateElement("Modelo");
xName.InnerText = c.Name;
xPhone.InnerText = c.Phone;
xCliente.AppendChild(xName);
xCliente.AppendChild(xPhone);
foreach (Matricula m in c.matricula)
{
xNr.InnerText = m.nr;
xMarca.InnerText = m.marca;
xModelo.InnerText = m.modelo;
xMatricula.AppendChild(xNr);
xMatricula.AppendChild(xMarca);
xMatricula.AppendChild(xModelo);
xMatriculas.AppendChild(xMatricula);
}
xCliente.AppendChild(xMatriculas);
xDoc.DocumentElement.AppendChild(xCliente);
}
i can add several Cliente to the root, but only the last Matricula in Matriculas is added.
Move
XmlNode xMatricula = xDoc.CreateElement("Matricula");
XmlNode xNr = xDoc.CreateElement("Nr");
XmlNode xMarca = xDoc.CreateElement("Marca");
XmlNode xModelo = xDoc.CreateElement("Modelo");
inside the inner for loop.
You are reusing the exact same node, you need to create a new node every time you want a new node in your document.

Deleting XML using a selected Xpath and a for loop

I currently have the following code:
XPathNodeIterator theNodes = theNav.Select(theXPath.ToString());
while (theNodes.MoveNext())
{
//some attempts i though were close
//theNodes.RemoveChild(theNodes.Current.OuterXml);
//theNodes.Current.DeleteSelf();
}
I have set xpath to what I want to return in xml and I want to delete everything that is looped. I have tried a few ways of deleting the information but it does't like my syntax. I found an example on Microsoft support: http://support.microsoft.com/kb/317666 but I would like to use this while instead of a for each.
Any comments or questions are appreciated.
Why not to use XDocument?
var xmlText = "<Elements><Element1 /><Element2 /></Elements>";
var document = XDocument.Parse(xmlText);
var element = document.XPathSelectElement("Elements/Element1");
element.Remove();
var result = document.ToString();
result will be <Elements><Element2 /></Elements>.
Or:
var document = XDocument.Load(fileName);
var element = document.XPathSelectElement("Elements/Element1");
element.Remove();
document.Savel(fileName);
[Edit] For .NET 2, you can use XmlDocument:
XmlDocument document = new XmlDocument();
document.Load(fileName);
XmlNode node = document.SelectSingleNode("Elements/Element1");
node.ParentNode.RemoveChild(node);
document.Save(fileName);
[EDIT]
If you need to remove all child elements and attributes:
XmlNode node = document.SelectSingleNode("Elements");
node.RemoveAll();
If you need to keep attributes, but delete elements:
XmlNode node = document.SelectSingleNode("Elements");
foreach (XmlNode childNode in node.ChildNodes)
node.RemoveChild(childNode);
string nodeXPath = "your x path";
XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);
XmlNode node = document.SelectSingleNode(nodeXPath);
node.RemoveAll();
XmlNode parentnode = node.ParentNode;
parentnode.RemoveChild(node);
document.Save("File Path");
You can use XmlDocument:
string nodeXPath = "your x path";
XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);//or document.LoadXml(...
XmlNode node = document.SelectSingleNode(nodeXPath);
if (node.HasChildNodes)
{
//note that you can use node.RemoveAll(); it will remove all child nodes, but it will also remove all node' attributes.
for (int childNodeIndex = 0; childNodeIndex < node.ChildNodes.Count; childNodeIndex++)
{
node.RemoveChild(node.ChildNodes[childNodeIndex]);
}
}
document.Save("your file path"));

Insert line in xml doc

I wanna insert in second line :
<?mso-application progid="Excel.Sheet"?>
but I'm started to think that it is impossible.
Here is my base code:
XmlDocument doc = new XmlDocument();
XmlReader reader = cmd.ExecuteXmlReader();
doc.LoadXml("<results></results>");
XmlNode newNode = doc.ReadNode(reader);
while (newNode != null)
{
doc.DocumentElement.AppendChild(newNode);
newNode = doc.ReadNode(reader);
}
Just Try like this
XmlNode XNode = doc.CreateProcessingInstruction("mso-application ", "progid=\"Excel.Sheet\"");
doc.AppendChild(XNode);
<?mso-application progid="Excel.Sheet"?> is a processing instruction not an element so you need to use the CreateProcessingInstruction Method

Categories

Resources