【问题标题】:xml error: Non white space characters cannot be added to contentxml 错误:不能将非空白字符添加到内容中
【发布时间】:2013-09-04 00:49:22
【问题描述】:

我正在尝试打开这样的 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");

我在第一行返回错误:

Non whitespace characters cannot be added to content.

xml 文件如下所示:

<?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>

【问题讨论】:

    标签: xml c#-4.0 linq-to-xml


    【解决方案1】:

    看起来您正试图将 XML 文件加载到 XDocument 中,但要这样做,您需要调用 XDocument.Load("C:\\temp\\contacts.xml"); - 您不能将 XML 文件传递​​到构造函数中。

    您还可以使用XDocument.Parse(stringXml); 加载XML 字符串。

    将第一行更改为:

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

    它会起作用的。

    作为参考,XDocument 构造函数有 4 个重载:

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

    您可能一直在考虑第三个 (XDocument(XDocument)),但要使用那个您必须编写:

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

    var doc = XDocument.Load("c:\\temp\\contacts.xml"); 足够时,这将是多余的。

    请参阅XDocument Constructor 了解详细信息。

    【讨论】:

      【解决方案2】:

      使用 XDocument.Parse(stringxml)

      【讨论】:

        【解决方案3】:
        XDocument xdoc=XDocument.load(path)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多