Get specific attribute of XmlNode - c#

I have an XmlNode, and its OuterXml is the next code I have posted. I need to know how to get The name and the age for each Campaign.
XmlNode Response = client.GetNamesAndAges(xmlRequest);
<Example>
<FromDate>12-05-2016</FromDate>
<ToDate>25-05-2016</ToDate>
<Campaigns>
<Campaign>
<Name>A</Name>
<age>2</age>
</Campaign>
<Campaign>
<Name>B</Name>
<age>1</age>
</Campaign>
</Campaigns>
<Status></Status>
</Example>

You can use XPath via SelectNodes() to get specific nodes/elements i.e Campaign elements in this case, and then print Name and age value from each Campaign :
var campaignList = Response.SelectNodes("Campaigns/Campaign");
foreach(XmlNode campaign in campaignList)
{
Console.WriteLine(campaign["Name"].InnerText);
Console.WriteLine(campaign["age"].InnerText);
}
BTW, Name and age are elements. Attributes in XML is used to reference something else i.e bar is the name of the attribute which value is baz in the following XML element <foo bar="baz"/>.

Use xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var campaign = doc.Descendants("Campaign").Select(x => new
{
name = (string)x.Element("Name"),
age = (int)x.Element("age")
}).ToList();
}
}
}

Related

Finding Specific xml nodes using XDocument

I am trying to find specific nodes in xml using XDocument. The xml also has a namespace which am importing.
Below is the xml specs
<?xml version="1.0" encoding="UTF-8"?>
<tns:response xmlns:tns="http://amazon.com/amazonservices">
<tns:responseDirect>
<tns:responseExtract>
<tns:A>ExtractName</tns:A>
</tns:responseExtract>
<tns:responses>
<tns:Name>Response1</tns:Name>
<tns:Include>No</tns:Include>
</tns:responses>
<tns:responses>
<tns:Name>Response2</tns:Name>
<tns:Include>Yes</tns:Include>
</tns:responses>
<tns:responses>
<tns:Name>Response3</tns:Name>
</tns:responses>
</tns:responseDirect>
I want to retrieve all responses and also only those nodes which have Include nodes present.
I am trying below code to fetch it but I am getting none of the nodes.
XDocument document = XDocument.Parse(xml);
var name = from nm in document.Elements("responses")
select nm;
Can anyone let me know how to fix the issue?I need to only fetch the response node.
Thanks in Advance
Try following :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XNamespace ns = doc.Root.GetNamespaceOfPrefix("tns");
var results = doc.Descendants(ns + "responses")
.Where(x => x.Elements(ns + "Include").Any())
.Select(x => new {
include = (string)x.Element(ns + "Include"),
name = (string)x.Element(ns + "Name")
}).ToList();
}
}
}

How to get all descendants with a particular attribute - Linq to Xml

<Grid>
<StringColumn Header="Name"/>
<DateColumn Header="Date"/>
</Grid>
There is probably an existing answer to this question, but I cannot seem to find it.
I need to find all xml elements which have an attribute of "Header"
The name of the element can be different.
How do I do that with Linq to XML?
This should give you the required elements:
XDocument document = ...;
var elementsWithHeader = document.Descendants()
.Where(e => e.Attributes().Any(a => a.Name == "Header"));
Something like this should work:
IEnumerable<XElement> elements =
from el in root.Elements("Grid")
where (string) el.Attribute("Header") != null
select el;
Use this:
var grid = XElement.Parse(#"<Grid>
<StringColumn Header=""Name""/>
<DateColumn Header=""Date""/>
</Grid>");
var elements = grid.XPathSelectElements(".//*[#Header]");
Using xml linq. Code is prints any Grid elements that have children with Header attributes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication7
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<XElement> headers = doc.Descendants("Grid").Where(x => x.Elements().Where(y => y.Attribute("Header") != null).Any()).ToList();
}
}
}

C# XDocument Read all Nodes from XML-File

I have an XML-file like this:
<Inventory>
<Item>
<Name>Super Mario Bros</Name>
<Count>14</Count>
<Price>29,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1985</Year>
<ProductID>001</ProductID>
</Item>
<Item>
<Name>The Legend of Zelda</Name>
<Count>12</Count>
<Price>34,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1986</Year>
<ProductID>002</ProductID>
</Item>
<Item>
<Name>Street Fighter</Name>
<Count>82</Count>
<Price>19,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1987</Year>
<ProductID>003</ProductID>
</Item>
</Inventory>
(There are more Items, but they are all the same, except for the values.)
Now I want to iterate through each Item and extract every value from each node. Here's what I've tried so far:
var xDocument = XDocument.Load(FilePath_CSVToXML);
string xml = xDocument.ToString();
StringBuilder sb = new StringBuilder();
foreach (XElement xe in xDocument.Descendants("Inventory")) {
sb.Append(xe);
}
Console.WriteLine(sb.ToString());
Console.ReadLine();
The code above properly displays the XML-file, but it keeps the Nodes. (Name, Count, Price, etc.) I only want the values.
You need to use the Value property, i.e. sb.Append(xe.Value).
Try code below. The innertag of Comment doesn't need angle brackets so remove.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication49
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
var results = doc.Descendants("Item").Select(x => new {
name = (string)x.Element("Name"),
count = (int)x.Element("Count"),
price = (decimal)x.Element("Price"),
comment = (string)x.Element("Comment"),
artist = (string)x.Element("Artist"),
publisher = (string)x.Element("Publisher"),
genre = (string)x.Element("Genre"),
year = (int)x.Element("Year"),
productID = (string)x.Element("ProductID")
}).ToList();
}
}
}

Deserialize XML containing a Dictionary

I have an XML file containing identifiers that I would like Get, the xml look like
<Dictionary
x:TypeArguments="x:String, x:Object"
xmlns="clr-namespace:System.Collections.Generic;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<List x:TypeArguments="x:Int32" x:Key="key" Capacity="4">
<x:Int32>60371408</x:Int32>
<x:Int32>60371409</x:Int32>
</List>
</Dictionary>
The identifiers that I want to get is 60371408, 60371409
I just found a solution :
Thank you for your reaction :D
Create an XmlSerializer:
var serializer = new XmlSerializer(typeof(Dictionary<string, object>));
...then deserialize. You haven't specified what form this XML is in, whether you have a string or a stream, for example. Here's how you'd deserialize an XML string:
var reader = new StringReader(xml);
var dict = serializer.Deserialize(reader);
Now you have your Dictionary<string, object>, but since values are plain objects, you'll need to cast the values:
var list = (List<int>)dict["key"];
Try xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
public class Program
{
const string FILENAME = #"c:\temp\test.xml";
public static void Main()
{
XDocument doc = XDocument.Load(FILENAME);
XElement dictionary = doc.Descendants().Where(x => x.Name.LocalName == "Dictionary").FirstOrDefault();
XNamespace xNs = dictionary.GetNamespaceOfPrefix("x");
var results = dictionary.Descendants(xNs + "Int32").Select(x => (int)x).ToList();
}
}
}

Read XML with ab:tag format using c#

I am new to xml, c#. I am following this tutorial: http://www.dotnetcurry.com/ShowArticle.aspx?ID=564
But my xml file is little different. The xml that I want to read in my c# code is this: http://api.nextag.com/buyer/synd.jsp?search=ipod&ver=15&token=AQB7dB$kB8ULvbGT&pid=1807
Code I am trying to read this xml is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
XElement xelement = XElement.Load("http://api.nextag.com/buyer/synd.jsp?search=ipod&ver=15&token=AQB7dB$kB8ULvbGT&pid=1807");
XNamespace nxtg = "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-01-11T08:31:30";
IEnumerable<XElement> employees = xelement.Elements();
// Read the entire XML
foreach (var employee in employees)
{
//Console.WriteLine(employee);
//Console.WriteLine(employee.Value);
if (employee.Element(nxtg + "search-category") == null)
continue;
else
Console.WriteLine(employee.Element(nxtg + "search-category").Value);
//Console.WriteLine(employee.Element("EmpId").Value);
}
But no luck. Anyone can help me please.
xelement.Elements() will return direct children of root element. In your case that will be elements nxtg:publisher, nxtg:search-query, nxtg:search-category etc. Thus nxtg:search-category is a direct child of root element, it also will selected as employee. That's why you can't find it in children of employee. You should do following instead:
// keep in mind, you have incorrect namespace value
XNamespace nxtg = "http://namespace.nextag.com/business-objects";
var searchCategory = xelement.Element(nxtg + "search-category");
var node = searchCategory.Element(nxtg + "node");
var displayName = (string)node.Element(nxtg + "display-name");
var value = (int)node.Element(nxtg + "value");

Categories

Resources