Home > Mobile >  How to add new lines to XML
How to add new lines to XML

Time:04-18

i have this XML-Structure:

<?xml version="1.0" ?>
<server xmlns="exampleServer">  
 <system-properties>
  <property name="prop0" value="null"/>
  <property name="prop1" value="true"/>
  <property name="prop2" value="false"/>
 </system-properties>    
</server> 

but i don't know how to add a new 'property' Line with two Attributes. Whats the best Way to do this? I have tried:

XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.DocumentElement;
string nameSpace = root.GetAttribute("xmlns");    
XmlNode nn = doc.CreateNode(XmlNodeType.Attribute, "property", 
nameSpace);

XmlAttribute attr = doc.CreateAttribute("name");
attr.Value = "prop3";
nn.AppendChild(attr);
attr = doc.CreateAttribute("value");
attr.Value = "value3";
nn.AppendChild(attr);
doc.AppendChild(nn);
doc.Save(path);

But the Error 'The Node has a wrong type' appears.

CodePudding user response:

The exception you are running into is caused by the fact you specify XmlNodeType.Attribute. What you really want is XmlNodeType.Element.

However, if you use XmlDocument.CreateElement(String, String) instead, you'll get an XmlElement object which has methods to make it easier to add attributes:

XmlDocument doc = new XmlDocument();
doc.Load(path);

// Create the new XML element and set attributes
string defaultNameSpace = doc.DocumentElement.GetAttribute("xmlns");    
var propertyElement = doc.CreateElement("property", defaultNameSpace);
propertyElement.SetAttribute("name", "prop3");
propertyElement.SetAttribute("value", "value3");

// Find the element to append the new element to
var nsMgr = new XmlNamespaceManager(doc.NameTable);
nsMgr.AddNamespace("ns", defaultNameSpace);
var sysPropNode = doc.SelectSingleNode("//ns:system-properties", nsMgr);

sysPropNode.AppendChild(propertyElement);
doc.Save(path);

See this fiddle for an example.

CodePudding user response:

It is better to use LINQ to XML API.

It is available in the .Net Framework since 2007. It is much easier and more powerful.

c#

void Main()
{
    const string inputFile = @"e:\Temp\Guest.xml";
    const string outputFile = @"e:\Temp\Guest_new.xml";

    XDocument xdoc = XDocument.Load(inputFile);
    XNamespace ns = xdoc.Root.GetDefaultNamespace();

    xdoc.Descendants(ns   "system-properties").FirstOrDefault()
        .Add(new XElement(ns   "property",
                 new XAttribute("name", "prop3"),
                 new XAttribute("value", "true")));

    xdoc.Save(outputFile);
}

Output

<?xml version="1.0" encoding="utf-8"?>
<server xmlns="exampleServer">
  <system-properties>
    <property name="prop0" value="null" />
    <property name="prop1" value="true" />
    <property name="prop2" value="false" />
    <property name="prop3" value="true" />
  </system-properties>
</server>
  • Related