Read a specific string from an xml file c# - c#

Hi i need to extract a specific string form my xml file. How can i go about this? i have searched the internet but cant find an answer specific enough for me to understand. ^^
I want to get my SavePath string using the corresponding GameName
heres my xml file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Game>
<entry>
<GameName>test</GameName>
<SavePath>C:\Users\allen\Downloads\GameOfLife\GameOfLife\obj\Debug\CoreCompileInputs.cache</SavePath>
<ExePath>C:\Users\allen\Downloads\GameOfLife\GameOfLife\obj\Debug\GameOfLife.exe</ExePath>
</entry>
<entry>
<GameName>test2</GameName>
<SavePath>C:\Users\allen\Downloads\GameOfLife\GameOfLife\obj\Debug\TemporaryGeneratedFile_E7A71F73-0F8D-4B9B-B56E-8E70B10BC5D3.cs</SavePath>
<ExePath>C:\Users\allen\Downloads\AdobeAIRInstaller.exe</ExePath>
</entry>
</Game>
and here's the code I've been trying to use
var xmlStr = File.ReadAllText(Properties.Resources.docname);
var str = XElement.Parse(xmlStr);
var result = str.Elements("entry")
.Where(x => x.Element("GameName").Value.Equals(SelectGame_Combobox.Text))
.Descendants("SavePath")
.ToString();

You are almost there. Just get rid of ToString() so it returns a collection of XElement (just one, of course), and then you can get it like this:
var result = str.Elements("entry").
Where(x => x.Element("GameName").Value.Equals(search)).Descendants("SavePath");
string value = result.First().Value;

Related

Parsing XML in C# creating a lists of user ID's

I am trying to create a list of user id's from an xml document in C#. Here is my latest try:
string xml = WebexAutomation.LstSummaryUser();
XDocument doc = XDocument.Parse(xml)
var result = doc.Descendants("webExId").Single().Value;
Console.WriteLine(result);
My XML looks like it has multiple users and I am trying to create list of each webExId
<?xml version="1.0" encoding="ISO-8859-1"?>
<serv:message xmlns:serv="http://www.webex.com/schemas/2002/06/service" xmlns:com="http://www.webex.com/schemas/2002/06/common" xmlns:use="http://www.webex.com/schemas/2002/06/service/user">
<serv:header>
<serv:response>
<serv:result>SUCCESS</serv:result>
<serv:gsbStatus>PRIMARY</serv:gsbStatus>
</serv:response>
</serv:header>
<serv:body>
<serv:bodyContent xsi:type="use:lstsummaryUserResponse" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<use:user>
<use:webExId>kkkk</use:webExId>
<use:firstName>kkkk</use:firstName>
<use:lastName>llllll</use:lastName>
<use:email>kkkkkk</use:email>
<use:registrationDate>06/07/2014 01:17:13</use:registrationDate>
<use:active>DEACTIVATED</use:active>
<use:timeZoneID>11</use:timeZoneID>
</use:user>
<use:user>
<use:webExId>jjjj</use:webExId>
<use:firstName>ssss</use:firstName>
<use:lastName>dddd</use:lastName>
<use:email>dfdfdf</use:email>
<use:registrationDate>06/10/2013 12:23:52</use:registrationDate>
<use:active>DEACTIVATED</use:active>
<use:timeZoneID>11</use:timeZoneID>
</use:user>
<use:matchingRecords>
<serv:total>44</serv:total>
<serv:returned>10</serv:returned>
<serv:startFrom>1</serv:startFrom>
</use:matchingRecords>
</serv:bodyContent>
</serv:body>
</serv:message>
Any suggestions?
Try this instead
var webExId = XName.Get("webExId", "http://www.tempuri.org");
var webExIds = doc.Descendants(webExId);

LINQ to XML extract based on condition

I have the following repetitive XML structure from which I have to create a List of an object:
<entries>
<entry>
<start>2013-10-01T00:00:00.000+02:00</start>
<end>2013-11-01T00:00:00.000+02:00</end>
<value>27.02</value>
<isExtracted>true</isExtracted>
</entry>
<entry>
<start>2013-11-01T00:00:00.000+02:00</start>
<end>2013-12-01T00:00:00.000+02:00</end>
<value>27.02</value>
<isExtracted>true</isExtracted>
</entry>
<entry>
<start>2013-12-01T00:00:00.000+02:00</start>
<end>2014-01-01T00:00:00.000+02:00</end>
<value>27.02</value>
</entry>
</entries>
I would like to extract only those elements that has the isExtracted xml tag!
What I do at the moment is the following:
var extract = xElemMaster.Elements("entries").Elements("entry")
.Where(elem => elem.Name.Equals("isExtracted"));
But I'm not getting any results out. What might have probably gone wrong?
You can use Any method
xElemMaster.Elements("entries")
.Elements("entry")
.Where(elem => elem.Elements("isExtracted").Any());
Or just try to get element and check for null:
xElemMaster.Elements("entries")
.Elements("entry")
.Where(elem => elem.Element("isExtracted") != null);
To make it more readable I would create an extension method and use it instead:
public static bool HasElement(this XElement source, string elementName)
{
return source.Element(elementName) != null;
}
xElemMaster.Elements("entries")
.Elements("entry")
.Where(elem => elem.Element.HasElement("isExtracted"));
You can search nodes and subnodes with Descendants, then use Any to check if IsExtracted exists.
var extract = xElemMaster.Descendants("entry")
.Where(w=>w.Elements("isExtracted").Any())
You might also want to check if isExtracted==True or false
var extract = x.Descendants("entry")
.Where(w => w.Elements("isExtracted").Any() && w.Element("isExtracted").Value=="true");

XmlDocument in an array like object

I googled for hours and didn't find anything.
I'm trying to make a Metro App which is reading from an online XML Service. Getting the XML is not the problem, i'm simply doing it like this ->
var xmlDoc = await XmlDocument.LoadFromUriAsync(new Uri(url));
but now the problem is, how to convert it into a list or something readable like this.
The XML I want to read is really huge and i don't want to go through all nodes with foreach.
A simple Array/List with all nodes and innerText as Value would be awesome.
Is this possible? If yes.. how ?
The structure of my XML is like this ->
<?xml version="1.0" encoding="UTF-8"?>
<city>
...
<credit>
...
</credit>
<forecast>
<date value="2013-11-08">
...
<time value="06:00">
...
</time>
<time value="11:00">
...
</time>
<time value="17:00">
...
</time>
<time value="23:00">
...
</time>
...
</date>
<date value="2013-11-09">
<same content here>
</date>
<date value="2013-11-09">
<same content here>
</date>
</forecast>
</city>
as you can see... there's a lot of information in the XML and I need nearly everything. In Actionscript I would realize it with a XMLList and make 3 Lists of the date Tags with content, so i can use
xmllist1.time[0] - xmllist1.time[3]
xmllist2.time[0] - xmllist2.time[3]
xmllist3.time[0] - xmllist3.time[3]
to get my data.
And now i want this XMLList in C#... I hope it's possible...Thx 4 help
If I understand you correctly, you want to parse the list of "city" items from the xml.
I do something similar using XDocument and Linq like this and it should work for you:
XDocument xdoc = <add your code to get xml from url>;
var ns = xdoc.Root.GetDefaultNamespace();
var cityList = from query in xdoc.Descendants(ns + "city")
select new CityItem
{
Date = (string)query.Element(ns + "date").Attribute("value").Value,
Time = (string)query.Element(ns + "time").Attribute("value").Value
};
public class CityItem
{
public string Date {get;set;}
public string Time {get;set;}
}

Retrieving a value from XML based on query parameter?

I have the following XML file, generated by my Windows Phone 8 app.
All works so far, but now I'd like to be able to query the file, and retrieve the associated with a particular -- So if I query it against "2222 it" would return "Location Name".
I have tried a few ways of doing this but I realised i didnt have a clue how to achieve this, even after hours of research. XML and LINQ confuse me immeasurably....so I woul really appreciate any tutorials or tips anyone could offer! Code thus far is below the sample XML document.
Thank you very much
<?xml version="1.0" encoding="utf-8"?>
<SmartSafe>
<Tag>
<tag>22222</tag>
<name>Location Name</name>
<latitude>xx.xxxxxxx</latitude>
<longitude>xx.xxxxxxx</longitude>
</Tag>
<Tag>
<tag>4444</tag>
<name>Location Name</name>
<latitude>xx.xxxxxxx</latitude>
<longitude>xx.xxxxxxx</longitude>
</Tag>
<Tag>
<tag>4444</tag>
<name>Location Name</name>
<latitude>xx.xxxxxxx</latitude>
<longitude>xx.xxxxxxx</longitude>
</Tag>
<Tag>
<tag>4444</tag>
<name>Location Name</name>
<latitude>xx.xxxxxxx</latitude>
<longitude>xx.xxxxxxx</longitude>
</Tag>
</SmartSafe>
Below is the section of the .cs which handles parsing the uid passed from the UriAssociationMapper.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.ContainsKey("uid"))
{
uid = int.Parse(NavigationContext.QueryString["uid"]);
}
base.OnNavigatedTo(e);
string stringUid = uid.ToString();
tagID.Text = stringUid;
//Retrieve tag name from xml
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
XDocument document;
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
if (storage.FileExists("/tagRegistry.xml"))
{
using (var stream = storage.OpenFile("/tagRegistry.xml", FileMode.Open))
{
document = XDocument.Load(stream);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Any help would be very much appreciated thank you!!
Your LINQ to XML query should look like that:
var value = doc.Root.Elements("Tag")
.FirstOrDefault(t => (string)t.Element("tag") == "22222")
.Element("name").Value;
However, It will throw NullReferenceException if element is not found, so you shouldn't use it if you're not sure XML document contains what you're looking for. If you're not sure about that, you should probably use following instead:
var tag = doc.Root.Elements("Tag")
.FirstOrDefault(t => (string)t.Element("tag") == "22222");
var value = tag == null ? string.Empty : (string)tag.Element("name");

Var with XML after Digest Authentication

After a Digest authentication:
var resultText = Digester.GrabResponse("/blabla");
I have this in the var resulText:
<?xml version="1.0" encoding="utf-8"?>
<response>
<HELLO>
<time>08:10</time>
<date>11.08.09</date>
<temp>35.5</temp>
<humi>37.7</humi>
</HELLO>
</response>
I tried to fetch the value of the date with XDocument but it didn't work.
This is really simple: -
XDocument xml = XDocument.Parse(resultText.ToString());
var date = (from n in xml.Descendants("HELLO")
select n.Element("date").Value).SingleOrDefault().ToString();
You need to use the XDocument.Parse method. Looks like you're passing an XML string as a URI to the Load method which obviously wont work.

Categories

Resources