CTABUYO
CTABUYO

Reputation: 712

Add element to XML C#

I´m trying to add the following element to a .XML on C#:

<Launch.Addon>
        <Name>IvAp</Name>
        <Disabled>False</Disabled>
        <Path>C:\Program Files (x86)</Path>
        <Commandline></Commandline>
</Launch.Addon>

With the following code:

XDocument xd1 = new XDocument();
xd1 = XDocument.Load(pathToAData + "\\dll.xml");

XElement root = new XElement("Launch Addon");
root.Add(new XElement("Name", "IvAp"));
root.Add(new XElement("Disable", "False"));
root.Add(new XElement("Path", "C:\\Program Files (x86)\\IVAO\\IvAp v2\\ivap_fsx_bootstrap.dll"));
root.Add(new XElement("Commandline"));
xd1.Element("Launch Addon").Add(root);
xd1.Save(pathToAData + "\\dll.xml");

But it throws an error in try {} catch {} block, I´ll be very thankful if you can help me

This is the error:

.System.Xml.XmlException: El carácter ' ', con valor hexadecimal 0x20, no puede incluirse en un nombre.

Upvotes: 0

Views: 112

Answers (2)

CodingYoshi
CodingYoshi

Reputation: 26989

You are almost there. First of all, as I mentioned in my comment, you need to remove the space from Launch Addon because XML element names cannot have a space.

Next, imagine this is your XML file:

<?xml version="1.0" encoding="utf-8"?>
<test>
    <addons>
    </addons>
</test>

Now you want to add something to it. You need to specify to which element you want to add the new element. So if you want to add an element to <test>, then you need to do this:

XElement root = new XElement("LaunchAddon");
root.Add(new XElement("Name", "IvAp"));
root.Add(new XElement("Disable", "False"));
root.Add(new XElement("Path", "C:\\Program Files (x86)\\IVAO\\IvAp v2\\ivap_fsx_bootstrap.dll"));
root.Add(new XElement("Commandline"));

xd1.Element("test").Add(root); //<-- See this, we are adding to test

If we wanted to add to <addons>, then we would do this:

xd1.Descendants("addons").First().Add(root);

Or you can use XPath to find the node to which you want to add the new node.

Upvotes: 1

Maurice
Maurice

Reputation: 357

Although you didn't gave us the error, I assume that the whitespace here

new XElement("Launch Addon");

causes the error. Because whitespaces inside tag names are not allowed as far as I know. But check the specs for more information: https://www.w3.org/TR/REC-xml/#NT-NameChar

Upvotes: 7

Related Questions