How to read, store and delete xml data in C# - c#

<SMSWall run="yes" nonstop="False">
<starttime>10:15:25 PM</starttime>
<endtime>10:15:25 PM</endtime>
</SMSWall>
<MediaPlayer run="yes" nonstop="False">
<starttime>10:15:25 PM</starttime>
<endtime>10:15:25 PM</endtime>
</MediaPlayer>
<Bidding run="yes" nonstop="False">
<starttime>10:15:25 PM</starttime>
<endtime>10:15:25 PM</endtime>
</Bidding>
This is my xml file. Now I want to read the xml, store the value in a variable (and also want the data to read from the string), and leave the .xml file so that it can be deleted.I also want to read the value node wise like:
XmlDocument document = new XmlDocument();
document.Load("Schedule.xml");
XmlNode ht=document.SelectSingleNode("SMSWall/#run");

Your current XML file is not in correct format (i.e save it as .xml and open it with IE, you will give an error). So you should add <root> ... </root> (or other name).
In all I think best way to treat with XML is using System.Xml.Linq library, like XDocument and XElement :
Loading data: XDocument.Load(filename);
Creating item: XElement root = new XElement("Root");
Searching: document.Descendants("Root"), ...
See MSDN for other samples.

I prefer to create a DataSet and then use it like this:
DataSet1 ds = new DataSet1();
ds.ReadXml("test.xml", XmlReadMode.ReadSchema);
//do something
ds.WriteXml("test.xml", XmlReadMode.ReadSchema);
A typed DataSet will provide you typed tables and rows. You can get rows by index or query. You can find more about the here.

Related

Get IPublishedContent To XDocument

I am new to the umbraco world. I am uploading an xml file using umbraco. I have a method that parses xml document on the backend using
System.Xml.Linq.
I am trying to get that file into an XDocument.
On the front end I have the following call that returns data
IPublishedContent doc = Umbraco.Media(CurrentPage.XMLfile);
but I dont know how to get that into a format that I can parse.
You can use TypedMedia method to have strongly typed object and use it's properties to retrieve / load file (e.g. from URL where it's stored inside the filesystem on your server).
Check: https://our.umbraco.org/documentation/getting-started/backoffice/property-editors/built-in-property-editors/media-picker and then use your preferred way to load up XML document from specific location.
It will look like e.g (untested, but should point you in the right direction):
var typedDocument = Umbraco.Media(CurrentPage.XMLfile);
if(typedDocument != null) {
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath(typedDocument.Url));
// ... do whatever you want with your doc
}

how to pass xml data to gridview?

Recently i am stuck with a problem during my development.I have some xml values in a variable (not in a seperate file).I transform the xml using xslt and displayed them using xml control in my webpage.NOw my requirement has been changed and I supposed to display the xml values in Gridview instead of xml control.
string getval= //some stuff where webservice returns xml.
// here I specified content to xmldynamic control
xmldynamic.TransformSource=//my xslt comes here..
Now I want to display the transformed XML in gridview.Is it possible...If possible how..
I surfed through net and identified that if xml is in a file, then xml data source can be used,transformed and define datasource to gridview.But in my case its in a variable.
There a lot of 3rd party Class / Software that does that.
For example for web an this is a powerfull app maybe you dont want this extensive app on your side but consider ExtJS
http://docs.sencha.com/extjs/4.2.2/
///
Also check this old topic for more
Is there an XML Editor with grid view similar to that of XMLSpy?
Try below steps:
1.) Load the XML data in a StringReader
2.) feed this StringReader object to ReadXml() method of DataSet
3.) Now bind this DataSet to your GridView.
This step is always tricky ( May be) as depending on the XML format Many times I needed to modify it slightly as : ds.Tables[0]; or ds.Tables[1]; etc...
Sample:
string xml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<Cameras>
<Camera>
<Model>Canon EOS-1D</Model>
<Price>$5219</Price>
</Camera>
<Camera>
<Model>Canon EOS-1D Mark IV</Model>
<Price>$5000</Price>
</Camera>
</Cameras>";
StringReader sr = new StringReader(xml); // Step 1
DataSet ds = new DataSet();
ds.ReadXml(sr); // Step 2
GridView1.DataSource = ds.Tables[0]; // Step 3
GridView1.DataBind();

XDocument Add multiple XElements

In my Windows Phone 8 C#/XAML .NET 4.5 Project, I'm trying to create an XDocument with similar structure:
<element1>
<subelement1>
</subelement1>
<subelement2>
...etc...
</subelement2>
</element1>
<element2>
<subelement1>
</subelement1>
<subelement2>
...etc...
</subelement2>
</element2>
The method creating the document looks like (simplified for the question purposes):
... createXML()
{
XDocument doc = new XDocument();
XElement elem1 = new XElement("element1");
elem1.Add(new XElement("subelement1"));
XElement elem2 = new XElement("element2");
doc.Add(elem1);
doc.Add(elem2);
}
But I keep getting InvalidOperationException saying that it would create a invalid document structure.
I know why - it would cause the document to have multiple "root nodes" - but I effectively need it that way.
This structure is needed for webservice done by third party, which recieves the document as a string.
So the question is "How to achieve this structure? Should I use some other XObject instead?"
(I know that probably the most simple solution would be to use collection of XElements...just askin' if there is another way out of curiosity)
The structure that you specified at the top of the post is illegal, because valid XML documents must have a single root element; your document has two elements at the top level, which is not allowed.
You can solve this problem by adding a root element at creation time, and then discarding it when reading the document;
document = new XDocument(new XElement("root", elem1, elem2));

How to change the data within elements in a XML file using C#?

I'm kind of new to XML files in C# ASP.NET. I have a XML in the below format:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Installation>
<ServerIP>192.168.20.110</ServerIP>
<DB_Name>USTCKT1</DB_Name>
<Username>jorame</Username>
<Password>Cru$%e20</Password>
<Table_PreFix>TCK</Table_PreFix>
</Installation>
I need to change the values within each element. For example, when an user clicks I should be able to replace 192.168.20.110 with 192.168.1.12.
How can I accomplish this? Any help will be really appreciated.
You should look at using the methods in the XDocument class. http://msdn.microsoft.com/en-us/library/bb301598.aspx
Specifically look at the methods: Load(string) - to load an XML file, Element() - to access a specific element and Save(string) - to save the XML document. The page on Element() has some sample code which can help.
http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx
You can do something like this using the XDocument class:
XDocument doc = XDocument.Load(file.xml);
doc.Element("Installation").Element("ServerIP").Value = "192.168.1.12";
//Update the rest of the elements
doc.Save(file.xml);
More Details
If you run into namespace issues when selecting your elements you will need to include the xml namespace in the XElement selectors eg doc.Element(namspace + "Installation")
In general, you can do it in the following steps:
Create a new XmlDocument object and load the content. The content might be a file or string.
Find the element that you want to modify. If the structure of your xml file is too complex, you can use xpath you find what you want.
Apply your modification to that element.
Update your xml file.
Here is a simple demo:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("file.xml"); // use LoadXml(string xml) to load xml string
string path = "/Installation/ServerIP";
XmlNode node = xmlDoc.SelectSingleNode(path); // use xpath to find a node
node.InnerText = "192.168.1.12"; // update node, replace the inner text
xmlDoc.Save("file.xml"); // save updated content
Hope it's helpful.

XML Illegal Characters in path

I am querying a soap based service and wish to analyze the XML returned however when I try to load the XML into an XDoc in order to query the data. am getting an 'illegal characters in path' error message? This (below) is the XML returned from the service. I simply want to get the list of competitions and put them into a List I have setup. The XML does load into an XML Document though so must be correctly formatted?.
Any advice on the best way to do this and get round the error would be greatly appreciated.
<?xml version="1.0" ?>
- <gsmrs version="2.0" sport="soccer" lang="en" last_generated="2010-08-27 20:40:05">
- <method method_id="3" name="get_competitions">
<parameter name="area_id" value="1" />
<parameter name="authorized" value="yes" />
<parameter name="lang" value="en" />
</method>
<competition competition_id="11" name="2. Bundesliga" soccertype="default" teamtype="default" display_order="20" type="club" area_id="80" last_updated="2010-08-27 19:53:14" area_name="Germany" countrycode="DEU" />
</gsmrs>
Here is my code, I need to be able to query the data in an XDoc:
string theXml = myGSM.get_competitions("", "", 1, "en", "yes");
XmlDocument myDoc = new XmlDocument();
MyDoc.LoadXml(theXml);
XDocument xDoc = XDocument.Load(myDoc.InnerXml);
You don't show your source code, however I guess what you are doing is this:
string xml = ... retrieve ...;
XmlDocument doc = new XmlDocument();
doc.Load(xml); // error thrown here
The Load method expects a file name not an XML itself. To load an actual XML, just use the LoadXml method:
... same code ...
doc.LoadXml(xml);
Similarly, using XDocument the Load(string) method expects a filename, not an actual XML. However, there's no LoadXml method, so the correct way of loading the XML from a string is like this:
string xml = ... retrieve ...;
XDocument doc;
using (StringReader s = new StringReader(xml))
{
doc = XDocument.Load(s);
}
As a matter of fact when developing anything, it's a very good idea to pay attention to the semantics (meaning) of parameters not just their types. When the type of a parameter is a string it doesn't mean one can feed in just anything that is a string.
Also in respect to your updated question, it makes no sense to use XmlDocument and XDocument at the same time. Choose one or the another.
Following up on Ondrej Tucny's answer :
If you would like to use an xml string instead, you can use an XElement, and call the "parse" method. (Since for your needs, XElement and XDocument would meet your needs)
For example ;
string theXML = '... get something xml-ish...';
XElement xEle = XElement.Parse(theXML);
// do something with your XElement
The XElement's Parse method lets you pass in an XML string, while the Load method needs a file name.
Why not
XDocument.Parse(theXml);
I assume this will be the right solution
If this is really your output it is illegal XML because of the minus characters ('-'). I suspect that you have cut and pasted this from a browser such as IE. You must show the exact XML from a text editor, not a browser.

Categories