构建 XDocument 时出错

Error when building an XDocument

使用以下示例 xml 包含一个副本:

<Persons>
  <Person>
    <PersonID>7506</PersonID>
    <Forename>K</Forename>
    <Surname>Seddon</Surname>
    <ChosenName />
    <MiddleName />
    <LegalSurname />
    <Gender>Male</Gender>
  </Person>
  <Person>
    <PersonID>6914</PersonID>
    <Forename>Clark</Forename>
    <Surname>Kent</Surname>
    <ChosenName>Clark</ChosenName>
    <MiddleName />
    <LegalSurname>Kent</LegalSurname>
    <Gender>Male</Gender>
  </Person>
  <Person>
    <PersonID>6914</PersonID>
    <Forename>Clark</Forename>
    <Surname>Kent</Surname>
    <ChosenName>Clark</ChosenName>
    <MiddleName />
    <LegalSurname>Kent</LegalSurname>
    <Gender>Male</Gender>
  </Person>
</Persons>

我有以下代码,我试图用过滤重复元素的 XPath 查询的输出构建 XDocument:

string outputXml = null;
var original = XDocument.Parse(xmlString);
string xpathFilterDups = "//Person[not(PersonID = following::Person/PersonID)]";
XDocument people = new XDocument("Persons", original.XPathSelectElements(xpathFilterDups));
outputXml = people.ToString();

我收到错误:

An exception of type 'System.ArgumentException' occurred in System.Xml.Linq.dll but was not handled in user code

非白色 space 字符无法添加到内容中。

这一行:

XDocument people = new XDocument("Persons", original.XPathSelectElements(xpath));

我做错了什么? :-\

您几乎可以忽略所有代码,问题是:

XDocument people = new XDocument("Persons");

您无法创建包含字符串的 XDocument,您需要添加一个元素:

XDocument people = new XDocument(
    new XElement("Persons",
        original.XPathSelectElements(xpathFilterDups)));