XmlDocument doc1 = new XmlDocument(); doc1.Load(filePath1); 

Document type:

 <?xml version="1.0" standalone="yes"?> <DBModel xmlns="http://tempuri.org/DBModel.xsd"> <Persons> <Id>1</Id> <Name>TestName</Name> <SecondName>TestSecName</SecondName> <ThirdName>TestThirdName</ThirdName> <FullName>TestSecName TestName TestThirdName</FullName> </Persons> </DBModel> 

If you add a node and save:

 var asd = doc1.CreateElement("Location"); asd.InnerText = Text; parent.AppendChild(asd); doc1.Save(filePath1.Replace(".xml", "_new.xml")); 

That will turn out:

  <Persons> <Id>1</Id> <Name>TestName</Name> <SecondName>TestSecName</SecondName> <ThirdName>TestThirdName</ThirdName> <FullName>TestSecName TestName TestThirdName</FullName> <Location xmlns="">Text</Location> </Persons> 

Respectively <Location xmlns=""> /// is not readable.

  • 2
    try doc1.CreateElement("Location", "http://tempuri.org/DBModel.xsd") - Sublihim
  • Works, thank you. Take out the answer so that I can accept it - DenisJNewb
  • 2
    or so doc1.CreateElement("Location", doc1.DocumentElement.NamespaceURI) , so that the namespace is not explicitly specified - kmv
  • @kmv yes for sure) - Sublihim

2 answers 2

The root element contains the namespace xmlns="http://tempuri.org/DBModel.xsd"
Therefore, when calling CreateElement you must specify this namespace.
Because this root namespace can be obtained directly from the document root ( doc1.DocumentElement.NamespaceURI )

 var asd = doc1.CreateElement("Location", doc1.DocumentElement.NamespaceURI); asd.InnerText = Text; parent.AppendChild(asd); doc1.Save(filePath1.Replace(".xml", "_new.xml")); 
  • Namespace root element may not coincide with parent namespace - Anton Shchyrov
  • @AntonShchyrov, well, I sort of know. ) I am in the context of the question asked - Sublihim

All elements belong to the http://tempuri.org/DBModel.xsd namespace. And you create a new element in an empty namespace. Hence the result

 <Location xmlns="">Text</Location> 

You need to create a new element also in the http://tempuri.org/DBModel.xsd namespace. There is an overloaded method for this.

 XmlDocument.CreateElement (String, String) 

where the second argument allows you to specify the required namespace. Total your code will be

 var asd = doc1.CreateElement("Location", "http://tempuri.org/DBModel.xsd"); 

or so

 var prfx = (parent.Prefix.Length > 0) ? parent.Prefix + ":" : ""; var asd = doc1.CreateElement(prfx + "Location", parent.NamespaceURI); 
  • In my opinion, your actions are not very beautiful. You are more technically correct to repeat what was said, why was it just not to edit that answer? We are not organizing races in reputation here ;-) - user227049
  • @FoggyFinder 1) At the time of publishing the answer, I did not see any other answers. 2) My answer is more general and universal. 3) If you think that my answer violates the rules of the community, you can mark it with anxiety and attract the moderator's attention - Anton Shchyrov