Var with XML after Digest Authentication - c#

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.

Related

How to get enclosure url with XElement C# Console

I read multiple feed from many sources with C# Console, and i have this code where i load XML From sources:
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
XElement xdoc = XElement.Load(sourceURLX);
How to get enclosure url and show as variable?
If I understand your question correctly (I'm making a big assumption here) - you want to select an attribute from the root (or 'enclosing') tag, named 'url'?
You can make use of XPath queries here. Consider the following XML:
<?xml version="1.0" encoding="utf-8"?>
<root url='google.com'>
<inner />
</root>
You could use the following code to retrieve 'google.com':
String query = "/root[1]/#url";
XmlDocument doc = new XmlDocument();
doc.Load(sourceURLX);
String value = doc.SelectSingleNode(query).InnerText;
Further information about XPath syntax can be found here.
Edit: As you stated in your comment, you are working with the following XML:
<item>
<description>
</description>
<enclosure url="blablabla.com/img.jpg" />
</item>
Therefore, you can retrieve the url using the following XPath query:
/item[1]/enclosure[1]/#url
With xml like below
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>title</title>
<link>https://www.link.com</link>
<description>description</description>
<item>
<title>RSS</title>
<link>https://www.link.com/xml/xml_rss.asp</link>
<description>description</description>
<enclosure url="https://www.link.com/media/test.wmv"
length="10000"
type="video/wmv"/>
</item>
</channel>
</rss>
You will get url by reading attribute
var document = XDocument.Load(sourceURLX);
var url = document.Root
.Element("channel")
.Element("item")
.Element("enclosure")
.Attribute("url")
.Value;
To get multiple urls
var urls = document.Descendants("item")
.Select(item => item.Element("enclosure").Attribute("url").Value)
.ToList();
Using foreach loop
foreach (var item in document.Descendants("item"))
{
var title = item.Element("title").Value;
var link = item.Element("link").Value;
var description = item.Element("description").Value;
var url = item.Element("enclosure").Attribute("url").Value;
// save values to database
}

Read a specific string from an xml file 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;

linq to xml: How to get value of a tag in an element in C#

I have following xml data.
<?xml version="1.0" encoding="utf-8" ?>
<mail>
<id>signUpConfirmation</id>
<subject>Activation</subject>
<body>
Hi, You account is activated \nRegards
</body>
</mail>
I need to read value from <body> tag depending on id I pass.
This is what I have tried
var xml = File.ReadAllText("C:\\Users\\DELL\\Documents\\Visual Studio 2012\\Projects\\Website\\Website\\Files\\Mails.xml");
var str = XElement.Parse(xml);
var result = from mail in str.Elements("mail")
where (string)mail.Element("id") == "signUpConfirmation"
select (string)mail.Element("body");
log.Debug("mail data:" + result.First());
I get error :
Sequence contains no elements.
Also, I want to access the value of id tag as well in the same query.
You have a couple of problems:
The id and body are not attributes but elements so you need to use the .Elements
You are using the XElement to parse the xml. It will start from the first element which is mail and then you are looking for child elements of it with the name of mail - which non exist. Use XDocument.
Code:
var result = (from mail in XDocument.Load("data.xml").Descendants("mail")
where mail.Element("id").Value == "signUpConfirmation"
select new {
Body = mail.Element("body").Value,
Subject = mail.Element("subject").Value
}).ToList();
var str = XDocument.Parse("<?xml version=\"1.0\" encoding=\"utf-8\" ?><mail> <id>signUpConfirmation</id> <subject>Activation</subject> <body>Hi, You account is activated \nRegards</body></mail>");
var result = from mail in str.Elements("mail")
where (string)mail.Element("id") == "signUpConfirmation"
select mail.Element("body");
result.FirstOrDefault();
Here is the code that work.
XDocument
instead of
XElement
End .Element as #DKR said.

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);

Load info from xml, save related (changed) info using c#

Friends,
My school project is having an xml data file:
<patients>
<patient>
<regNo>2012/Mar/003</regNo>
<name>Jhon</name>
<add>Somewhere</add>
<mobile>0000</mobile>
.
.
.
<stay>2</stay>
<costofroom>100</costofroom>
<total>200</total>
</patient>
</patients>
My Windowsform "EditPatients_Load" is able to fetch all info of patient Jhon, and now let's assume that the Admin needs to change some information in the form & resubmit.
Then how to write back all values to Jhon's account in the same xml
file????
I'm not able to makeup the logical code, even if I check the node if (patients.paptient.name = "nameComboBox.text").... how to make sure that I'm writing other values on proper place?
Rgrdz,
Try this:
//string xml =
//#"<patients><patient><regNo>2012/Mar/003</regNo><name>Jhon</name><add>Somewhere
//</add><mobile>0000</mobile><stay>2</stay><costofroom>100</costofroom><total>200</total>
//</patient></patients>";
XDocument xmlDoc = XDocument.Load(#"c:\abc.xml");
var items = (from item in xmlDoc.Descendants("patient")
where item.Element("name").Value == "Jhon"
select item);
if (items.Count() > 0)
{
var item = items.First();
item.SetElementValue("add", "New New Address");
xmlDoc.Save(#"c:\abc.xml", SaveOptions.None);
}
You can get single element using
var item = (from item in xmlDoc.Descendants("patient")
where item.Element("name").Value == "Jhon"
select item).FirstOrDefault();
then update it using SetElementValue() method.
//Updated Xml
<?xml version="1.0" encoding="utf-8"?>
<patients>
<patient>
<regNo>2012/Mar/003</regNo>
<name>Jhon</name>
<add>New Address</add>
<mobile>0000</mobile>
<stay>2</stay>
<costofroom>100</costofroom>
<total>200</total>
</patient>
</patients>
Reference:
Update XML with C# using Linq
I would take the xml serialization/deserialization route to solve this:
http://support.microsoft.com/kb/815813
How to Deserialize XML document
That way you can work with objects and not have to parse xml files manually.
If you're using .NET 3.5 onward you can use the XDocument class like the following. I'm assuming your content is in a .xml file.
XDocument xdoc = XDocument.Load(#"C:\Tmp\test.xml");
//this would ensure you get the right node and set its text content/value
xdoc.Element("patients")
.Element("patient").Element("add").Value = "some new address?";
xdoc.Save(#"C:\Tmp\test.xml");
The file test.xml would change to:
<patients>
<patient>
<regNo>2012/Mar/003</regNo>
<name>Jhon</name>
<add>some new address?</add>
<mobile>0000</mobile>
<stay>2</stay>
<costofroom>100</costofroom>
<total>200</total>
</patient>
</patients>

Categories

Resources