将XAttribute添加到XElement时出现重复错误

时间:2012-10-18 12:37:08

标签: c# xml xpath

我有一个大的xml文件,我正在解析一个xpath来插入值。这是我正在插入一些值的xml文件的一部分:

<SERVICES>
    <RELATIONSHIPS>
         <RELATIONSHIP xlink:from="fromValue01" xlink:to="toValue01" />
         <RELATIONSHIP xlink:from="fromValue02" xlink:to="toValue02" />
         <RELATIONSHIP xlink:from="fromValue03" xlink:to="toValue03" />
         <RELATIONSHIP xlink:from="fromValue04" xlink:to="toValue04" />
         <RELATIONSHIP xlink:from="fromValue05" xlink:to="toValue05" />
         <RELATIONSHIP xlink:from="fromValue06" xlink:to="toValue06" />
         <RELATIONSHIP xlink:from="fromValue07" xlink:to="toValue07" />
    </RELATIONSHIPS>
<SERVICES>

现在,当我想添加更多具有相同属性但具有不同值的RELATIONSHIP个节点(例如<RELATIONSHIP xlink:from="fromValue08" xlink:to="toValue08" />)时,我总是会遇到Duplicate Attribute错误。这将是我正在解析的xpath的例子:

/SERVICES/RELATIONSHIPS/RELATIONSHIP[@xlink:from="fromValue08" and @xlink:to="toValue08"]

解析器太大了,只能粘贴到这里,我确信它工作正常,因为它插入所有节点就好了,这里只有这部分给我带来了一些麻烦。 我还用Altova检查了xpath并且它有效。

我的问题是:添加一个具有相同属性但XML中允许的值不同的节点?如果是,为什么Visual Studio总是抛出这个错误?

2 个答案:

答案 0 :(得分:1)

我似乎已经弄清楚了。解析器上的问题不像在xpath上那么大。我错过了xpath上的索引。所以我的解析器选择了第一个RELATIONSHIP,它确实有重复的XAttributes。我刚刚在属性条件之前添加了索引。所以最后看起来像是:

/SERVICES/RELATIONSHIPS/RELATIONSHIP[8][@xlink:from="fromValue08" and @xlink:to="toValue08"]

我不知道这是否是正确的xpath语法,如果索引应该在条件之后,但对于我的解析器,它正在工作。

答案 1 :(得分:0)

与您的XPath请求相关的确可能是RELATIONSHIPS

缺少索引