xml error: Non white space characters cannot be added to content

user603007 picture user603007 · Sep 4, 2013 · Viewed 23.3k times · Source

I am trying to open an xmldocument like this:

var doc = new XDocument("c:\\temp\\contacts.xml");
var reader = doc.CreateReader();
var namespaceManager = new XmlNamespaceManager(reader.NameTable);
namespaceManager.AddNamespace("g", g.NamespaceName);
var node = doc.XPathSelectElement("/Contacts/Contact/g:Name[text()='Patrick Hines']", namespaceManager);
node.Value = "new name Richard";
doc.Save("c:\\temp\\newcontacts.xml");

I returns an error in the first line:

Non whitespace characters cannot be added to content.

The xmlfile looks like this:

<?xml version="1.0" encoding="utf-8"?>
<Contacts xmlns:g="http://something.com">
  <Contact>
    <g:Name>Patrick Hines</g:Name>
    <Phone>206-555-0144</Phone>
    <Address>
      <street>this street</street>
    </Address>
  </Contact>
</Contacts>

Answer

Tim picture Tim · Sep 4, 2013

It looks like you're attempting to load an XML file into an XDocument, but to do so you need to call XDocument.Load("C:\\temp\\contacts.xml"); - you can't pass an XML file into the constructor.

You can also load a string of XML with XDocument.Parse(stringXml);.

Change your first line to:

var doc = XDocument.Load("c:\\temp\\contacts.xml");

And it will work.

For reference, there are 4 overloads of the XDocument constructor:

XDocument();
XDocument(Object[]);
XDocument(XDocument);
XDocument(XDeclaration, Object[]);

You might have been thinking of the third one (XDocument(XDocument)), but to use that one you'd have to write:

var doc = new XDocument(XDocument.Load("c:\\temp\\contacts.xml"));

Which would be redundant when var doc = XDocument.Load("c:\\temp\\contacts.xml"); will suffice.

See XDocument Constructor for the gritty details.