Confusion about How to populate xmlfile - c#

I need to create a xml file programmatically like below.
<Players>
<Player>
<Name>C.Ronaldo</Name>
<Team>Man Utd</Team>
<Position>Midfielder</Position>
</Player>
</Players>
The problem is that the xml file which is created is not what I expect .How can fix this code
Thanks in advance
XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-16", null));
XElement root = new XElement("Players");
xdoc.Add(root);
XElement player = new XElement("Player");
XElement[] el = {
new XElement("Name","xxx"),
new XElement("Team","dfdf"),
new XElement("Position","dsds")
};
xdoc.Root.Add(el);
xdoc.Save("myxml.xml", SaveOptions.None);
MessageBox.Show("ok");

The simpliest solution for your code would be to replace
xdoc.Root.Add(el);
with this:
player.Add(el);
xdoc.Root.Add(player);

Related

XML Namespace prefix only on root

I am creating an XML document using the Task Factory XML Output Destination task though the output needs some tweaking and I can't seem to find a way to do this within the task so figured I would be able to do this via the script component with C#.
This is the XML I am working with
<?xml version="1.0" encoding="utf-8"?>
<CSDS xmlns="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
<CYP000>
<C000010>1.0</C000010>
</CYP000>
</CSDS>
And I need to change the XML to look like:
<?xml version="1.0" encoding="utf-8"?>
<CSDS:CSDS xmlns:CSDS="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
<CYP000>
<C000010>1.0</C000010>
</CYP000>
</CSDS>
I have tried creating a new XDocument declaring the namespace and adding the source elements in but this adds the namespace to all elements.
string xmlFile = #"C:\Temp\csds.xml";
string newXmlFile = #"C:\Temp\csds-new.xml";
XDocument sourceXml = XDocument.Load(xmlFile);
XNamespace ns = "http://www.datadictionary.nhs.uk/messages/CSDS-v1-0";
XDocument newXml = new XDocument(new XDeclaration("1.0", "utf-8", null));
XElement newRoot = new XElement(ns + "CSDS",
new XAttribute(XNamespace.Xmlns + "CSDS", ns.NamespaceName));
newRoot.Add(sourceXml.Root.Elements());
newRoot.Save(newXmlFile);
Output
<?xml version="1.0" encoding="utf-8"?>
<CSDS:CSDS xmlns:CSDS="http://www.datadictionary.nhs.uk/messages/CSDS-v1-0">
<CSDS:CYP000>
<CSDS:C000010>1.0</CSDS:C000010>
</CSDS:CYP000>
</CSDS:CSDS>
I have found that doing the following after loading my file works along with the rest of my code:
foreach (var descendants in sourceXml.Root.Descendants())
descendants.Name = descendants.Name.LocalName;

exception occurs while saving XML using c#

I am trying to update an existing XML file by adding a new child node using c#.
Everything is OK if I save it by new name but I want to update the same file and while doing it, got the following exception:
System.IO.IOException:Process cannot access the file... because it is
being used by another process
Here is my code: (I am trying to add a new default node)
XmlDocument doc = new XmlDocument();
string path = #"C:\Debug\default.xml";
doc.Load(path);
XmlNode NName = doc.CreateElement("default");
XmlNode SNO = doc.CreateElement("SNo");
SNO.InnerText = "2";
NName.AppendChild(SNO);
doc.DocumentElement.AppendChild(NName);
doc.Save(path);
Also XML file:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<default>
<SNo>1</SNo>
</default>
</NewDataSet>
If you are sure the file is only being used by your process, then simply read it into a byte array, close the file, then save it again:
(I am using .net 4.0 for this sample):
XmlDocument doc = new XmlDocument();
byte[] content = File.ReadAllBytes(path);
using (var memStream = new MemoryStream(content))
{
doc.Load(memStream);
}
XmlNode NName = doc.CreateElement("default");
XmlNode SNO = doc.CreateElement("SNo");
SNO.InnerText = "2";
NName.AppendChild(SNO);
doc.DocumentElement.AppendChild(NName);
doc.Save(path);

Can not save string / node to XML WP8

I am reading the contents of an xml file perfectly into a longlistselector with tap events attached. All working great. The file sits in the main assets folder of the project.
Now i would also like to add strings/ nodes to my simple XML, but for some reason i can't find the right syntax to save it to the file.
My xml file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<phrases>
<item><name>What is your name?</name></item>
<item><name>How old are you?</name></item>
</phrases>
Now I tried the following inside of a click event of a button:
XDocument xDoc = XDocument.Load("phrases.xml");
var contactsElement = new XElement("item",
new XElement("name", "blalllllaaaallaala")));
xDoc.Add(contactsElement);
xDoc.Save("phrases.xml");
VS2013 tells me that the xDoc.Save("phrases.xml") has invalid arguments. When i read from that file i provide the same path, so i dont understand what is expected here? Please give some suggestions.
Just try out with this snippet...
// load original XML from the stream
XDocument loadedData = XDocument.Load(stream);
// create a new parent XML structure (new root) and load the original nodes
var newXml = new XDocument(new XElement("Histories"));
newXml.Root.Add(loadedData.Root);
// create the new node
var contactsElement = new XElement("item",
new XElement("name", "blalllllaaaallaala")));
NewNode.Add(contactsElement);
// add the new node
newXml.Root.Add(NewNode);
// save the stream
newXml.Save(stream);
For more have a look here too.

need to add comments in an existing xml document

I need to add comments in an existing xml document.a sample xml is shown below i need to write code in c#. XML serialization was used to generate this xml
any help would be great...
thanks in advance
<?xml version="1.0" encoding="utf-8"?>
<Person>
<Name>Job</Name>
<Address>10dcalp</Address>
<Age>12</Age>
</Person>
Try it like this:
string input = #"<?xml version=""1.0"" encoding=""utf-8""?><Person><Name>Job</Name><Address>10dcalp</Address><Age>12</Age></Person>";
XDocument doc = XDocument.Parse(input);
XElement age = doc.Root.Element("Age");
XComment comm = new XComment("This is comment before Age");
age.AddBeforeSelf(comm);
This code gets the document, finds the element named "Age" which is expected to be under the root element ("Person") and adds comment before it.
You can use XmlWriter to write the comment in following way:
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream);
writer.WriteStartDocument();
writer.WriteComment("Add comment here");
Now, you serialize XmlWriter instance through your serializer.

Add XDeclaration to XDocument after it's constructed

I have an XmlSerializer which I use to Serialize an object to an XDocument.
var doc = new XDocument();
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, object);
}
After this is done, I want to add a XDeclaration:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
I construct this XDeclaration as described below:
var decl = new XDeclaration("1.0", "UTF-8", "no");
However, when I try to add this XDeclartion to my XDocument, I get the following error:
System.ArgumentException : Non white space characters cannot be added to content.
I searched Google for some time but all I've found is adding the XDeclaration to the constructor of the XDocument which in my case (when filling it with a XmlWriter) is not acceptable.
Use property XDocument.Declaration
EDIT:
Sample code:
var xmlSerializer = new XmlSerializer(typeof(int));
var doc = new XDocument();
var decl = new XDeclaration("1.0", "utf-8", "no");
doc.Declaration = decl;
using (var writer = doc.CreateWriter())
{
xmlSerializer.Serialize(writer, 1);
}
doc.Save(File.Create("x.xml"));
This code produced following output:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<int>1</int>

Categories