Get XML values from XML database string in C# - c#

I’m trying to get the values of an xml snippet that is stored in my database but can’t seem to make it work. They are all coming back null... The xml looks like this:
<fields>
<field id="EmployeeID">1002240002</field>
<field id="JobType">Web Manager</field>
<field id="CompanyCode">R6297C</field>
</fields>
My Code, with the string from the database is below.
string xml = "<fields><field id=\"EmployeeID\">1002240002</field><field id=\"JobType\">Web Manager</field><field id=\"CompanyCode\"> R6297C </field></fields>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
var n = xmlDoc.GetElementById("EmployeeID ");
if (n != null)
{
var employeeId = xmlDoc.GetElementById("EmployeeID ").InnerText;
}
Any help on this? I know I am missing something easy here... Thanks!

You can use following XPath query
string xpath = "field[#id='EmployeeID']";
XmlNode fieldNode = xmlDoc.DocumentElement.SelectSingleNode(xpath);
var id = Int32.Parse(fieldNode.InnerText);
Or Linq to Xml
var id = (from f in xdoc.Descendants()
where (string)f.Attribute("id") == "EmployeeID"
select (int)f).Single();
Or with fluent interface
var id = xdoc.Descendants()
.Where(f => (string)f.Attribute("id") == "EmployeeID")
.Select(f => (int)f)
.Single();
BTW xdoc is an instance of XDocument class:
var xdoc = new XDocument(xml);

Related

Looping through xmlnodes using Xdocument

I have an xml string like this
<Test>
<ConnectionParameters>
<ConnectionParameter DisplayName="asd" Id="cgfh" IsPassword="false" IsRequired="true"> </ConnectionParameter>
<ConnectionParameter DisplayName="asdasd" Id="fgh" IsPassword="false" IsRequired="true"></ConnectionParameter>
<ConnectionParameter DisplayName="asdasd" Id="hdfh" IsPassword="false" IsRequired="true"></ConnectionParameter>
<ConnectionParameter DisplayName="asdad" Id="dfgdf" IsPassword="false" IsRequired="true"> </ConnectionParameter>
</ConnectionParameters>
</Test>
How can I loop through each "ConnectionParameter" tag inorder to get the attributes like Id,DisplayName etc using xdocument?
I tried like this,
XDocument xdoc = new XDocument();
xdoc= XDocument.Parse(fileContent);
var saveResult = from b in xdoc.Descendants("ConnectionParameters")
select new
{
success = (string)b.Element("ConnectionParameter").Attribute("Id").Value ?? string.Empty,
};
But it only returns the first node only
You're currently looping through all the ConnectionParameters elements (of which there's only one) and selecting the first ConnectionParameter element (using the Element call). You want to just loop through the ConnectionParameter elements:
// Note the lack of creating a new XDocument for no reason
XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = from b in xdoc.Descendants("ConnectionParameter")
select new
{
success = (string) b.Attribute("Id") ?? ""
};
Or to avoid creating an anonymous type for no obvious reason, and using plain "dot notation" as the query expression isn't helping you much:
XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = xdoc.Descendants("ConnectionParameter")
.Select(b => (string) b.Attribute("Id") ?? "");
If you prefer to make the parent element names explicit, you could use:
XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = xdoc.Element("Test")
.Element("ConnectionParameters")
.Descendants("ConnectionParameter")
.Select(b => (string) b.Attribute("Id") ?? "");
Or:
XDocument xdoc = XDocument.Parse(fileContent);
var saveResult = xdoc.Root
.Element("ConnectionParameters")
.Descendants("ConnectionParameter")
.Select(b => (string) b.Attribute("Id") ?? "");
Load your xml into xDocument, then you can do something like this (can't remember exact syntax)
xDoc.Root.Descendants("ConnectionParameters").Attribute("DisplayName").Value;

simple way to read xml data using linq

I have a xml structure like this. Can anyone help with a simple linq function to read this xml structure.The itemEntry node repeats according to data. I tried to read the xml using the method below,but i am getting no records in the list. Is this method here correct way to get the details...
List<CX_ITEMLIST> sList =
(from e in XDocument.Load(param.FileName).Root.Elements("itemEntry")
select new CX_ITEMLIST
{
TITLE = (string)e.Element("title"),
YEAR = (string)e.Element("year"),
ITEMNAME = (string)e.Element("itemname"),
CATRYLIST =
(
from p in e.Elements("categorylist").Elements("categories")
select new CATLIST
{
IDTYPE = (string)p.Element("categoryid"),
IDNUMBER = (string)p.Element("categoryName")
}).ToList()
}).ToList();
<itemslist>
<itemInformation>
<itemdate>01/23/2014</itemdate>
<itemcount>57</itemcount>
</itemInformation>
<itemEntry>
<title>Title1</title>
<year>2013</title>
<itemname>testname</itemname>
<categorylist>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
</categorylist>
</itemEntry>
<itemEntry>
<title>Title1</title>
<year>2013</title>
<itemname>testname</itemname>
<categorylist>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
<categories>
<categoryid>Category1</categoryid>
<categoryName>Category2</categoryName>
</categories>
</categorylist>
</itemEntry>
</itemslist>
You should try with XDocument.
XDocument xdoc = XDocument.Load("file.xml");
The System.Xml.XLinq namespace contains some awesome objects to make this easy.
var xDoc = XDocument.Parse(xml); // load your xml string, or use XDocument.Load() to load an xml file
var itemEntries = xDoc
.Root // refers to itemEntries node
.Descendants("itemEntry"); // gets all itemEntry nodes in an IEnumerable object
This gets you an IEnumerable<XNode> of all the itemEntry nodes.
From there you can do what you need, save the values to a business object, etc.
The above method works properly, i found the issue, my xml tag was having namespace attribute. i tried to get the namespace and append it with Elements while reading
XNamespace ns = xDocument.Root.Attribute("xmlns").Value;
List<CX_ITEMLIST> sList =
(from e in XDocument.Load(param.FileName).Root.Elements(ns + "itemEntry")
select new CX_ITEMLIST
{
TITLE = (string)e.Element(ns + "title"),
YEAR = (string)e.Element(ns + "year"),
ITEMNAME = (string)e.Element(ns + "itemname"),
CATRYLIST =
(
from p in e.Elements(ns + "categorylist").Elements(ns + "categories")
select new CATLIST
{
IDTYPE = (string)p.Element(ns + "categoryid"),
IDNUMBER = (string)p.Element(ns + "categoryName")
}).ToList()
}).ToList();

Get node property of XmlDocument in C#

I'm using this xml structure:
<park>
<car title="Ferrari" available="true">
<url>http://www.ferrari.com/</url>
</rss>
</park>
And this is my code in C#:
XmlDocument doc = new XmlDocument();
doc.Load("Settings.xml");
XmlNodeList list = doc.SelectNodes("/park/car");
foreach (XmlNode item in list)
{
string x = item["#title"].InnerText;
}
I just want to get "title" property but i can't get it working. I'm using "#" but without success.
Try this code:
string x = item.Attributes["title"].Value;
I suggest you to use LINQ to XML for parsing xml:
var xdoc = XDocument.Load("Settings.xml");
var titles = xdoc.XPathSelectElements("//park/car")
.Select(c => (string)c.Attribute("title"));
Or without XPath:
var titles = xdoc.Descendants("park")
.Elements("car")
.Select(c => (string)c.Attribute("title"));

Parsing a xml string & retrieving its attribute Value using Linq to XML C#

I am quite new to Linq to XML & trying to Parse a xml string & retrieve its attribute Value using Linq to XML in C#.
My XML string looks like :
<configuration xmlns:lui="http://www.xyz.com/UITags">
<pub id="pubId1" lang="en-US">
<configitem name="visible" value="visible"/>
<configitem name="working_status" value="unlocked"/>
<configitem name="prepared" value="prepared"/>
</pub>
.....
.....
<pub id="Pub2" lang="es-XM">...</pub>
....
....
</configuration>
I want to fetch the value of 'id' & 'lang' from pub node & value of attribute named 'working_status' from configitem Node.
Now as I am getting the above xml as a string parameter (i.e. myXmlData), by doing
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXmlData);
XmlNodeList publicationsNodeList = doc.SelectNodes("//configuration/pub");
...
...
Then I have to loop through using foreach, which I want to avoid as much as possible.
Can anyone help me how to achieve this using Linq to XML in C#, rather then conventional way.
Following LINQ to XML query will return sequence of anonymous objects with id, lang, and working status of pub elements:
var xdoc = XDocument.Parse(myXmlData);
var query =
from p in xdoc.Root.Elements("pub")
let ws = p.Elements("configitem")
.FirstOrDefault(c => (string)c.Attribute("name") == "working_status")
select new {
Id = (string)p.Attribute("id"),
Lang = (string)p.Attribute("lang"),
WorkingStatus = (ws == null) ? null : (string)ws.Attribute("value")
};
For your sample xml it returns two objects with following data:
{
Id = "pubId1",
Lang = "en-US",
WorkingStatus = "unlocked"
},
{
Id = "Pub2",
Lang = "es-XM",
WorkingStatus = null
}
var query = from x in xdoc.Descendants("pub")
select new
{
Id = (string)x.Attribute("id"),
Lang = (string)x.Attribute("lang"),
Name = x.Descendants("configitem").Select(y => y.Attribute("name").Value).FirstOrDefault(y => y == "working_status")
};

C# XML How to retrive innerText of field by attribute?

Here is the XML sample:
<?xml version="1.0" ?>
<XMLScreen xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CX>80</CX>
<CY>24</CY>
<Formatted>true</Formatted>
<Field>
<Location position="1" left="1" top="0" length="69" />
<Attributes Base="226" Protected="false" FieldType="High" />
*SDC SCHEDULING CATEGORY UPDATE
</Field>
</XMLScreen>
I want to retrive the Inner text of each field based on its Location position.
What I have so far is:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(myEm.CurrentScreenXML.GetXMLText());
XmlNodeList fields = xmlDoc.GetElementsByTagName("Field");
MessageBox.Show("Field spot: " + i + " Contains: " + fields[i].InnerText);
And I want to be able to just extract the inner text of the field by passing in a number of the location position. So if I say foo[i] I want to be able to get the innertext
*SDC SCHEDULING CATEGORY UPDATE
You should use a xpath search query :
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
int nodeId = 4;
XmlNode node = xmlDoc.SelectSingleNode(String.Format(#"//Location[#position='{0}']", nodeId));
if (node != null)
{
String field = node.ParentNode.InnerText;
}
Something like that, with XDocument instead of XmlDocument (well, if you're not in .net 3.5 or higher, we'll have a problem).
private string GetTextByLocationId(XDocument document, int id)
{
var field = document.Descendants("Field").FirstOrDefault(m => m.Element("Location").Attribute("position").Value == id.ToString());
if (field == null) return null;
return field.Value;
}
and usage
var xDocument = XDocument.Load(<pathToXmlFile or XmlReader or string or ...>);
var result = GetTextByLocationId(xDocument, 1);
EDIT
or if you want a dictionary with :key = position / value = text
private static Dictionary<int, string> ParseLocationAndText(XDocument document)
{
var fields = document.Descendants("Field");
return fields.ToDictionary(
f => Convert.ToInt32(f.Element("Location").Attribute("position").Value),
f => f.Value);
}
Try,
XElement root = XElement.Parse(myEm.CurrentScreenXML.GetXMLText());
XElement field = root.XPathSelectElement(
string.Format("Field[Location/#position='{0}']", 1));
string text = field.Value;
You will need to use the following using to use XPath with XElements.
using System.Xml.XPath;

Categories

Resources