read remote xml from server using c# - c#

Hello i am trying to get simple xml file from server and to read the data so i can convert it to list. I was try few lib and code with no success so far. I am getting the xml content in one line without any tags <> and the count is always 0 zero. The XML string. I need to get the data that inside camp tag
<campaigns>
<mainPage>http://example.com</mainPage>
<orderPage>https://www.example.co.il/adver/</orderPage>
<totalCount>3</totalCount>
<onLineCount>2</onLineCount>
<campaignList>
<camp id="557">
<name>test1</name>
<status>on</status>
<rating>5</rating>
<url>http://example.com/557</url>
</camp>
<camp id="559">
<name>test1</name>
<status>on</status>
<rating>5</rating>
<url>http://example.com/559</url>
</camp>
<camp id="660">
<name>test1</name>
<status>off</status>
<rating>5</rating>
<url>http://example.com/660</url>
</camp>
</campaignList>
And the c# code i am trying so far
XElement xelement = XElement.Load("http://example.com/test.xml");
var name = from nm in xelement.Elements("camp")
where (string)nm.Element("status") == "on"
select nm;
Response.Write(name.Count());
foreach (XElement xEle in name)
{
Response.Write(xEle);
}

XElement.Elements() means search in children tags. I think what you need is Descendants() or xelement.Element("campaigns").Element("campaignList").Elements("camp")

Related

Get Xml content into a string from a subchild using c#

It is my first time posting, and I am very new to C#, so I appreciate the help. I have so many variations of this code that are close to what I need, but I can't get on my own.
I am trying to get the contents of a sub-child in an XML sting using c#. This is the sting I receive:
<?xml version="1.0" encoding="UTF-8"?>
<activation>
<activationOutput>
<AID>7706a84f-5sef5-4b49-891c-98414ebb61d5</AID>
<protectionKeyId>18305465463798407</protectionKeyId>
<activationString>encoded xml string</activationString>// What I need
</activationOutput>
<activationInput>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
<isvPermission></isvPermission>
<endUserPermission></endUserPermission>
</activationAttribute>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
</activationAttribute>
<comments></comments>
</activationInput>
</activation>
I need to get the activationString value out into a string. Having the other elements would be nice, but I only care about getting into a string v2c called. The information in between the tags is another encoded XML string.
I first bring the sting into an XML element using:
XElement rootActivation = XElement.Parse(encodedActivationResponse, LoadOptions.SetLineInfo);
What has got me stumped is how to get the sub child out as a string. Using XElement element gets me the values for all of the children under ActivationOutput, but I only need the last one.
string activationOutput = rootActivation.Element("activationOutput").Value;
It sends me a long unusable string
7706a84f-5sef5-4b49-891c-98414ebb61d518305465463798407encodedxmlstring
I've also tried:
IEnumerable<XElement> activationString = rootActivation.Elements("activationString");
It looked promising, but I don't know how to get the value out as a string. It shows as
{System.Xml.Linq.Extenstions.GetDescendantsXElement>}
I was hoping that I could take the variable and push it into a string using:
string v2c = activationString.ToString;
But that does not work either
Your attempt
string activationOutput = rootActivation.Element("activationOutput").Value;
does give you a concatenation of all the text() nodes that are children of <activationOutput>. Obviously, that's not what you want.
To solely get the <activationString>'s text() node use
string activation =
(string)rootActivation.Element("activationOutput").Element("activationString").Value;
One restriction of this approach is: it only gets the first of each elements.
If that is the only element called activationString you could just do
string activationString = XDocument.Parse("xmlFilePathHere").Descendents("activationString").FirstOrDefault().Value;
In VB.Net
Dim rootActivation As XElement
'for testing
rootActivation = <activation>
<activationOutput>
<AID>7706a84f-5sef5-4b49-891c-98414ebb61d5</AID>
<protectionKeyId>18305465463798407</protectionKeyId>
<activationString>encoded xml string</activationString>
</activationOutput>
<activationInput>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
<isvPermission></isvPermission>
<endUserPermission></endUserPermission>
</activationAttribute>
<activationAttribute>
<attributeName></attributeName>
<attributeValue></attributeValue>
</activationAttribute>
<comments></comments>
</activationInput>
</activation>
Dim activationString As String = rootActivation.<activationOutput>.<activationString>.Value

I want to create an array containing my xmldocument nodes in c#

Hello I have created an xml file with motivational quotations, and I want to read those quotations into an array.
Here is what my xml file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<MotivationalQuotes>
<quotation>
<quote>Life is about making an impact, not making an income</quote>
<author>Kevin Kruse</author>
</quotation>
<quotation>
<quote>Whatever the mind of man can conceive and believe, it can achieve</quote>
<author>Napoleon Hill</author>
</quotation>
</MotivationalQuotes>
I am trying to store each individual quotation (without the author) into an array, so far I have the below code working - which creates a message box and iterates through the xml file displaying the text from each quotation.
1) How can I modify this code to create a string array, where each item in the array is a quotation (i.e. each item in the array is the contents that is currently being displayed to the messagebox in my foreach loop?
2) how do I return a random item from the array, once it is created?
3) As an extension to my question... my xml file only has motivational quotes in at the moment, but it will have more inspirational, funny etc... how can I specify to only include quotations into the array if they are inside the MotivationalQuotes tag.
Thanks for the help!
public void motivate()
{
XmlDocument doc = new XmlDocument();
doc.Load("quotations.xml");
XmlNode Node = doc.DocumentElement;
foreach (XmlNode Node1 in Node.ChildNodes)
{
MessageBox.Show(Node1.FirstChild.InnerText);
}
}
You should use XDocument and LINQ.
To get all quotes
using System.Xml.Linq;
var quotes = XDocument
.Load("quotations.xml")
.Descendants("quote")
.Select(q => q.Value)
.ToArray();

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>

Returning XML Data from Root on Window 7 Phone

I am having difficulty trying to return values from an XML file. Here is an example of the XML:
<xml>
<item1>Whatever</item1>
<video>
<caption>Video Title</caption>
<width>1280</width>
<height>720</height>
</video>
<element1>Results One</element1>
<element2>Results Two</element2>
</xml>
I am calling the data like this:
XElement xmlData = XElement.Parse(e.Result);
var list = new List<VideoUrl>();
foreach (XElement item in xmlData.Elements("xml"))
{
var element1 = item.Element("element1").Value;
var element2 = item.Element("element2").Value;
list.Add(new VideoUrl
{
etc...
});
and then assigning the data to a list box to return the values. Problem is I am trying to return XML items "element1" and "element2" but nothing is returned when i run the emulator. If I change the code to return Video > Caption it works fine. I feel like its something real simple I am missing. Any ideas or code samples to fix this would be much appreciated. Thanks in advanced.
xmlData is the <xml> element, so xmlData.Elements("xml") will return no values - there are no xml elements directly under xmlData. Given that it's the root, you know there's only one node, so you can just do:
var element1 = (string) xmlData.Element("element1");
var element2 = (string) xmlData.Element("element2");
Note that by casting to string instead of using the Value property, you end up with a null reference if the element doesn't exist, instead of an exception being thrown.

Direct access and edit to an xml node, using properties

El Padrino showed a solution:
How to change XML Attribute
where an xml element can be loaded directly (no for each..), edited and saved!
My xml is:
<?xml version="1.0" encoding="ISO-8859-8"?>
<g>
<page no="1" href="page1.xml" title="נושא 1">
<row>
<pic pos="1" src="D:\RuthSiteFiles\webSiteGalleryClone\ruthCompPics\C_WebBigPictures\100CANON\IMG_0418.jpg" width="150" height="120">1</pic>
</row>
</page>
</g>
and I need to select a node by two attributes(1. "no" in the page tag and "pos" in the pic tag)
I've found :
How to access a xml node with attributes and namespace using selectsinglenode()
where direct access is possible but beside the fact that I dont understand the solution, I think it uses the xpath object which can't be modified and save changes.
What's the best way to
access directly an xml node (I'm responsible that the node will be unique)
edit that node
save changes to the xml
Thanks
Asaf
You can use the same pattern as the first answer you linked to, but you will need to include the conditions on the attributes in the XPath. Your basic XPath would be g/page/row/pic. Since you want the no attribute of page to be 1, you add [#no='1'] as a predicate on page. So, the full XPath query is something like g/page[#no='1']/row/pic[#pos='1']. SelectSingleNode will return a mutable XmlNode object, so you can modify that object and save the original document to save changes.
Putting the XPath together with El Padrino's answer:
//Here is the variable with which you assign a new value to the attribute
string newValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xmlFile);
XmlNode node = xmlDoc.SelectSingleNode("g/page[#no='1']/row/pic[#pos='1']");
node.Attributes["src"].Value = newValue;
xmlDoc.Save(xmlFile);
//xmlFile is the path of your file to be modified
Use the new, well-designed XDocument/XElement instead of the old XmlDocument API.
In your example,
XDocument doc = XDocument.Load(filename);
var pages = doc.Root.Elements("page").Where(page => (int?) page.Attribute("no") == 1);
var rows = pages.SelectMany(page => page.Elements("row"));
var pics = rows.SelectMany(row => row.Elements("pic").Where(pic => (int?) pic.Attribute("pos") == 1));
foreach (var pic in pics)
{
// outputs <pic pos="1" src="D:\RuthSiteFiles\webSiteGalleryClone\ruthCompPics\C_WebBigPictures\100CANON\IMG_0418.jpg" width="150" height="120">1</pic>
Console.WriteLine(pic);
// outputs 1
Console.WriteLine(pic.Value);
// Changes the value
pic.Value = 2;
}
doc.Save(filename);

Categories

Resources