editing xml using C# - c#

I have that xml document :
<?xml version="1.0" encoding="utf-8" ?>
<reminders>
<reminder>
<Title>Alarm1</Title>
<Description>Desc1</Description>
<Time>03/07/2012 10:11AM</Time>
<snooze>1</snooze>
<repeat>None</repeat>
</reminder>
<reminder>
<Title>Alarm2</Title>
<Description>Desc2</Description>
<Time>03/07/2012 10:11AM</Time>
<snooze>15</snooze>
<repeat>Daily</repeat>
</reminder>
</reminders>
And say i would like to create a full reminder child like :
<reminder>
<Title>NEW-Alarm</Title>
<Description>New-Desc</Description>
<Time>03/07/2012 10:11AM</Time>
<snooze>15</snooze>
<repeat>Daily</repeat>
</reminder>
How can i do that in C# ?
And also i`d like to edit some child like from :
<Title>NEW-Alarm</Title>
to be
<Title>Modified-NEW-Alarm</Title>
I am fresh to XML and i really did my best , actually i am opening like 13 webpages for xml but none of them has what i really need, so i`ll truly appreciate your help.

I would take a look at using XDocument. You may want to search the web for examples of creating XML with it but this answer from the unstoppable Jon Skeet is a good place to start:
XML file creation using XDocument in C#
Hope that helps.
Also see these links:
http://www.codeproject.com/Articles/169598/Parse-XML-Documents-by-XMLDocument-and-XDocument
http://www.leghumped.com/blog/2009/06/30/c-xml-with-xdocuments/
http://forums.asp.net/t/1736899.aspx/1?Help+using+XDocument+in+LINQ+with+ASP+Net+C+

Load the doc with XDocument class
Add a element (edit PATH with your data) :
XElement newEl = new XElement(new XElement("reminder",
new XElement("Title", "NEW-Alarm"),
new XElement("Description", "New-Desc"),
new XElement("Time", "03/07/2012 10:11AM"),
new XElement("snooze", "15"),
new XElement("repeat", "Daily")));
doc.Root.Add(newEl);
doc.Save(PATH);
To change, we must first find the element (with LINQ) and then apply the SetValue method.
http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.setvalue.aspx

You need to look into the XDocument as a way to open your XML Document and then take a look at the documentation for XElement to see how easy it is to build nodes.
Each documentation page has great samples.

Related

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.

Write xml from textbox to existing xml file without replacing old text, just adding new

So... I have 2 textboxes and 1 button.
And when I input data to those textboxes, and click the button, I would like it to enter xml file and add new element with attributes to it, without replacing it.
After a lot of browsing I managed to do something that replaced all text in my xml file, or I got an error, so I decided to post a question here.
So this is how my xml file looks:
<library>
<book name="Her way" price="20"></book>
<book name="His way" price="20"></book>
</library>
and what I'm trying to do is to insert:
<book name="Their way" price="22"></book>
bellow last one so it would look like:
<library>
<book name="Her way" price="20"></book>
<book name="His way" price="20"></book>
<book name="Their way" price="22"></book>
</library>
And every time I click button again, it adds it same way, ofc I would change name and price in textbox.
I came up with this code, but I am fairly new to xml so I don't know how to modify it or make it work.
XDocument doc = XDocument.Load("booklibrary.xml");
doc.Add(new XElement("book",
new XAttribute("name", textBox1.Text),
new XAttribute("price", textBox3.Text)));
doc.Save("booklibrary.xml");
Thank you!
Don't use XDocument if you aren't working with namespaces. Just use an XElement and your code will work:
var library = XElement.Load("booklibrary.xml");
library.Add(new XElement("book",
new XAttribute("name", textBox1.Text),
new XAttribute("price", textBox3.Text)));
library.Save("booklibrary.xml");
Because you used XDocument, Add tried to add the new element next to the root element <library> instead of inside it, causing an exception because there can be only one root element. Several illustrative examples can be found on MSDN.
By using XElement as shown above, this problem is fixed.
I would use LINQ to XML instead, very easy to use and tons of functionality!:
XElement ele = XElement.Load("booklibrary.xml");
ele.Element("library").Add(
new XElement("book",
new XAttribute("name", textBox1.Text),
new XAttribute("price", textBox3.Text)));
ele.Save();
This is much cleaner, and it uses the new .NET stuff.

Need to parse a xml string

I need to a parse an xml string(.NET, C#) which , unfortunately, is not well formed.. the xml stream that i am getting back is
<fOpen>true</fOpen>
<ixBugParent>0</ixBugParent>
<sLatestTextSummary></sLatestTextSummary>
<sProject>Vantive</sProject>
<ixArea>9</ixArea>
I have tried using a xml reader, but its crashing out because it thinks ,and rightfully so, there are 2 node elements wheneever it tries to parse
Is there something that I can do with this ? I cant change the XML, cause I have no control of the code that sends the XML back ..
Any help, would be appreciated.
Thanks and Regards
Gagan Janjua
I think you can use the XmlParserContext in one of the XmlTextReader overloads to specify that the node type is an XmlNodeType.Element, similar to this example from MSDN (http://msdn.microsoft.com/en-us/library/cakk7ha0.aspx):
XmlTextReader tr = new XmlTextReader("<element1> abc </element1>
<element2> qrt </element2>
<?pi asldfjsd ?>
<!-- comment -->", XmlNodeType.Element, null);
while(tr.Read()) {
Console.WriteLine("NodeType: {0} NodeName: {1}", tr.NodeType, tr.Name);
}
What you are getting back is a well-formed XML fragment but as you pointed out, not a well-formed XML document. Can you
wrap a top-level element around the returned elements? or
reference the returned XML fragment as an external entity from within a shell XML document, and pass the shell document to the XML reader?

In XML, what are the nodes with question marks called, and how do I add them in C#?

Here's an example of an XML file created in InfoPath:
<?xml version="1.0" encoding="UTF-8"?>
<?mso-infoPathSolution solutionVersion="1.0.0.1" productVersion="12.0.0" PIVersion="1.0.0.0" href="file:///C:\Metastorm\Sample%20Procedures\InfoPath%20samples\Template1.xsn" name="urn:schemas-microsoft-com:office:infopath:Template1:-myXSD-2010-07-21T14-21-13" ?>
<?mso-application progid="InfoPath.Document" versionProgid="InfoPath.Document.2"?>
<my:myFields xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-07-21T14:21:13" xml:lang="en-us">
<my:field1>hello</my:field1>
<my:field2>world</my:field2>
</my:myFields>
What are those top 3 nodes with the question mark called... and how do I create them in C#?
So far I have this:
XmlDocument xmldoc;
XmlDeclaration xmlDeclaration;
xmldoc=new XmlDocument();
xmlDeclaration = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "") as XmlDeclaration;
xmlDeclaration.Encoding = "UTF-8";
xmldoc.AppendChild(xmlDeclaration);
This works fine for the top XML declaration node , but how do I create the next two?
Thanks in advance :)
These are called processing instructions. Add 'em using XmlDocument.CreateProcessingInstruction.
Those are called processing instructions. You can use the XmlProcessingInstruction class to interact with them in an XmlDocument.
As with most elements defined within an XmlDocument, you cannot instantiate it directly; you must use the appropriate factory method on XmlDocument (CreateProcessingInstruction in that particular case.)
Thanks for explaining that these are processing instructions. Using CreateProcessingInstruction as suggested, here is the solution:
xmlPi = xmldoc.CreateProcessingInstruction("mso-infoPathSolution", "solutionVersion=\"1.0.0.1\" productVersion=\"12.0.0\" PIVersion=\"1.0.0.0\" href=\"file:///C:\\Metastorm\\Sample%20Procedures\\InfoPath%20samples\\Template1.xsn\" name=\"urn:schemas-microsoft-com:office:infopath:Template1:-myXSD-2010-07-21T14-21-13\"");
xmldoc.AppendChild(xmlPi);

Categories