Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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> 
like image 735
user603007 Avatar asked Sep 04 '13 00:09

user603007


People also ask

What are non white-space characters?

Non-whitespace character: \S\S matches any non-white-space character. It is equivalent to the [^\f\n\r\t\v\x85\p{Z}] regular expression pattern, or the opposite of the regular expression pattern that is equivalent to \s , which matches white-space characters. For more information, see White-Space Character: \s.


2 Answers

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.

like image 54
Tim Avatar answered Sep 17 '22 21:09

Tim


Use XDocument.Parse(stringxml)

like image 34
tichra Avatar answered Sep 21 '22 21:09

tichra