gpt4 book ai didi

c# - 构建 XDocument 时出错

转载 作者:太空宇宙 更新时间:2023-11-03 23:34:36 25 4
gpt4 key购买 nike

使用以下包含一个重复项的示例 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

不能将非空白字符添加到内容中。

在这一行:

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

我做错了什么? :-\

最佳答案

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

XDocument people = new XDocument("Persons");

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

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

关于c# - 构建 XDocument 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30977855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com