xml 错误:无法将非空白字符添加到内容中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18603722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
xml error: Non white space characters cannot be added to content
提问by user603007
I am trying to open an xmldocument like this:
我正在尝试打开这样的 xmldocument:
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:
xmlfile 如下所示:
<?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>
回答by Tim
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.
看起来您正在尝试将 XML 文件加载到 XDocument 中,但为此您需要调用XDocument.Load("C:\\temp\\contacts.xml");- 您不能将 XML 文件传递给构造函数。
You can also load a string of XML with XDocument.Parse(stringXml);.
您还可以使用 .xml 加载一串 XML 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 XDocumentconstructor:
作为参考,XDocument构造函数有 4 个重载:
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:
您可能一直在考虑第三个 ( XDocument(XDocument)),但要使用那个,您必须这样写:
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.
什么时候var doc = XDocument.Load("c:\\temp\\contacts.xml");就足够了,这将是多余的。
See XDocument Constructorfor the gritty details.
有关详细信息,请参阅XDocument 构造函数。
回答by tichra
Use XDocument.Parse(stringxml)
使用 XDocument.Parse(stringxml)
回答by hadi.sh
XDocument xdoc=XDocument.load(path)

