Append New Element in XML VB or C# - c#

I apologize if this question is too easy for you as I am just starting to learn how XML works. What I am trying to do is to append a new element to App/Library and for example I started with this.
<?xml version="1.0" encoding="utf-8"?>
<App>
<Library>
<Count>100</Count>
<Track>
<TrackID>1</TrackID>
<Name>New York</Name>
<Artist>Snow Patrol</Name>
</Track>
</Library>
</App>
what I am trying to do is to add another track to my existing XML.
<Track>
<TrackID>2</TrackID>
<Name>Chasing Cars</Name>
<Artist>Snow Patrol</Name>
</Track>

There are a couple of ways to deal with xml manipulation in .NET. The older style using System.Xml.XmlDocument or using System.Xml.Linq.XDocument approach.
Here is an example on how to do it using XmlDocument:
var xml = "Baz";
var doc = new XmlDocument();
doc.LoadXml(xml); //Load up the original xml string into XmlDocument object
var fooNode = doc.SelectSingleNode("//foo"); //use xpath to get to the top level foo element
var newBar = doc.CreateElement("bar"); //Create a new bar element and assign it's inner text
newBar.InnerText = "Baz2";
fooNode.AppendChild(newBar); //append the newly created bar element to foo
and here is an example on how to do it using XDocument (which is much more simpler):
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><foo><bar>Baz</bar></foo>";
var xdoc = XDocument.Parse(xml); //Load up the original xml string into Linq XDocument object
xdoc.Root.Add(new XElement("bar", "Bar2")); //Add <bar>Bar2</bar> to foo (which is root of the document)
Here is a running example:
https://dotnetfiddle.net/vY7Vag

Related

How to get the name of elements/attributes in xml files and write these into another new xml file using LINQ

I am new to c#. Right now I am trying to get the name of some specific elements in an xml file and create a new xml file for these.
I have tried with LINQ, so that I can parse the xml and get the name of some elments that I want.
I do not want to use console.writeline to output this name. Instead I would like to create a new xml file and save these names in it.
Can anyone give me some tips?
The following is example data I would like to parse:
<root>
<Package>
<Class name="EnterpriseArchitect">
<Operation/>
</Class>
<Class name="ZachmanFramework">
<Operation/>
</Class>
</Package>
</root>
I want to get the attribute name of the element Class and save it in a new xml file like this:
<root>
<EnterpriseArchitect/>
<ZachmanFramework/>
</root>
The following is my c# code, but I can not reach the goal:
XDocument xdoc = XDocument.Load(#"C:\Users\jsc\Desktop\123456.xml");
XDocument xNew = new XDocument();
var datatype = xdoc.Root.Elements("Package").Elements("Class")
foreach (var dut in datatype)
{
var dataTypeName = dut.Attribute("name").Value;
xNew.Add(new XElement(dataTypeName));
}
xNew.Save(#"C:\Users\jsc\Desktop\1234567.xml");
Please, read my comments to the question.
This should work:
XDocument srcdoc = XDocument.Load("sourceFileName.xml");
List<XElement> names = srcdoc.Descendants("Class")
.Select(x=> new XElement(x.Attribute("name").Value))
//.Distinct() //uncomment this if duplicate values aren't allowed
.ToList();
XDocument newdoc = new XDocument();
XElement root = new XElement("root");
root.Add(names);
newdoc.Add(root);
newdoc.Save("newFileName.xml");
Good luck!

Adding a root node to Xml Document having a existing root node in C#

I have an xml document that may look like this
<Stuff>
<SomeStuff></SomeStuff>
</Stuff>
and I want to add a new root to this document, to make it look like this
<Root>
<Stuff>
<SomeStuff></SomeStuff>
</Stuff>
</Root>
This is what i tried
string inputXml = " <Stuff>
<SomeStuff></SomeStuff>
</Stuff>";
XmlDocument firstLossRootNode = new XmlDocument();
firstLossRootNode.LoadXml("<Root />");
var economyDocument = = XDocument.Parse(inputXml);
firstLossRootNode.DocumentElement.AppendChild(economyDocument.Document);
I was trying to Append it has a child but i was getting compile time error
Is there a way to do this in c# using Xdocument class.
In your example, you are using the XmlDocument class for your firstLossRootNode, but the XDocument class for your economyDocument. Is this by design? If not, the following code will do what you are trying to do:
using System;
using System.Xml.Linq;
string inputXml = "<Stuff><SomeStuff></SomeStuff></Stuff>";
XDocument firstLossRootNode = XDocument.Parse("<Root />");
XDocument economyDocument = XDocument.Parse(inputXml);
firstLossRootNode.Root.Add(economyDocument.FirstNode);

Very simple XML reading in C#.NET

I want to read the following XML file:
Words.xml:
<?xml version="1.0" encoding="utf-8" ?>
<words>
<word>Bat</word>
<word>Dog</word>
<word>Car</word>
</words>
..using XDocument. I keep getting a "Non white space characters cannot be added to content" error with this code:
XDocument doc = new XDocument("words.xml");
foreach (XElement element in doc.Descendants("word"))
{
Console.WriteLine(element.Value);
}
You need to load the document like this:
XDocument doc = XDocument.Load("words.xml");
The reason your original code fails is you are using XDocument (Object[]) constructor that normally expects list of XElement objects like:
var doc = new XDocument(new XElement("Root"));

C# Adding a root to an XDocument

I have a string that contains an XML, lets say like this:
<Novels>
<Book>
<Title>Cat in hat</Title>
<Price>12</Price>
</Book>
</Novels>
I want to make an XDocument that looks like this:
<Booklist>
<Novels>
<Book>
<Title>Cat in hat</Title>
<Price>12</Price>
</Book>
</Novels>
</Booklist>
I can load the xml string into an XDocument using XDocument doc = XDocument.Parse(xmlString);
How would I load the document under a new root. I can think of something like creating a new XDocument with the root I want and then using a for loop to add the nodes as children, but is there an easier way of doing this?
XDocument yourResult = new XDocument(new XElement("Booklist", doc.Root));
var doc = new XDocument(new XElement("Booklist", source.Root));
It does not require any parsing at all. There is a deep copy of XElement made, so there is also no references between old and new documents.

Delete a whole Node from an Xml Advertisement file?

I am trying to delete a whole XmlNode which matches a certain condition
The format of my xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<Advertisements>
<Ad>
<ImageUrl>image/Hydrangeas.jpg</ImageUrl>
<NavigateUrl>www.google.com</NavigateUrl>
<AlternateText>nbfndbf</AlternateText>
<ID>0</ID>
<Impressions>1</Impressions>
</Ad>
</Advertisements>
My deleting code:
XElement x =
new XElement("Ad",
new XElement("ImageUrl", lblImageURL.Text),
new XElement("NavigateUrl", lblImageURL.Text),
new XElement("AlternateText", lblAlternateText.Text),
new XElement("ID", lblID.Text),
new XElement("Impressions", lblfrequency.Text));
string filepath = Request.PhysicalApplicationPath.ToString() + "Adrotator.xml";
XmlDocument xD = new XmlDocument();
xD.LoadXml(x.ToString());
XmlNode xN = xD.FirstChild;
xN.ParentNode.RemoveChild(xN);
**xD.Save(filepath);**
I am getting an error Invalid XML document. The document does not have a root element.
You can use linq to xml to achieve this here exmple how to remove node where value ID = 0
var q = (from c in doc.Descendants("Advertisements")
from v in c.Elements("Ad")
where (int) v.Element("ID") == 0
select v).Remove();
here is another example using xpath
doc.XPathSelectElement("Advertisements/Ad[ID = 0]").Remove();
You create a new XDocument (doc) with the following code:
XDocument doc = XDocument.Load(filepath);
Is there something in the Xml file (with a root element)? Also, you don't seem to use doc in the code, so it's at least not required.

Categories