通过XAttribute的值合并XDocuments

时间:2018-04-26 05:48:28

标签: c# xml linq

我已设法合并具有相同XElement值的XAttribute - s,但我无法弄清楚如何找到不在附加内容中的List<XElement> XDocument

<!--xml1-->
<SecurityPrivileges>
  <SecurityPrivilege Principal="user1">
    <Privilege Type="FileSystem" AccessType="read" Action="Add">c:\log</Privilege>
  </SecurityPrivilege>
</SecurityPrivileges>

<!--xml2-->
<SecurityPrivileges>
  <SecurityPrivilege Principal="user2">
    <Privilege Type="FileSystem" AccessType="read" Action="Add">c:\log</Privilege>
  </SecurityPrivilege>
</SecurityPrivileges>

<!--expected result-->
<SecurityPrivileges>
  <SecurityPrivilege Principal="user1">
    <Privilege Type="FileSystem" AccessType="read" Action="Add">c:\log</Privilege>
  </SecurityPrivilege>
  <SecurityPrivilege Principal="user2">
    <Privilege Type="FileSystem" AccessType="read" Action="Add">c:\log</Privilege>
  </SecurityPrivilege>
</SecurityPrivileges>

这是我不完整的方法。我合并了主体并检查权限是否已经存在,但我无法弄清楚如何将新主体附加到result

internal XDocument AppendXml(XDocument original, XDocument append)
{
    XDocument result = XDocument.Parse($"<{root}></{root}>");

    //Find similar principals
    foreach (XElement originalElement in original.Root.Elements())
    {
        XElement resultElement = originalElement;
        string originalPrincipal = originalElement.Attribute(PRINCIPAL).Value;

        //Matching principal in the append xml - there can be only one
        XElement appendPrincipal = append.Root.Elements().Where(x =>
            x.Attribute(PRINCIPAL).Value.Equals(originalPrincipal)).ElementAt(0);

        if (!appendPrincipal.IsEmpty)
        {
            foreach (XElement appendPrivilege in appendPrincipal.Elements())
            {
                //Check if Privilege appending is necessary
                if (!originalElement.Elements()
                     .Any(oPrivilege => HasPrivilege(oPrivilege, appendPrivilege)))
                {
                    resultElement.Add(appendPrivilege);
                }
            }
        }
        result.Root.Add(resultElement);
    }

    //TODO add new principals to result
    List<XElement> appendPrincipals = append.Root.Elements().Where(...);

    return result;
}

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了。它并不像我想的那样容易阅读...

foreach (XElement appendElement in append.Root.Elements())
{
    string appendPrincipal = appendElement.Attribute(PRINCIPAL).Value;
    //If the result does not contain an XElement with this attribute
    if (!result.Root.Elements()
         .Any(x => x.Attribute(PRINCIPAL).Value.Equals(appendPrincipal)))
    {
        result.Root.Add(appendElement);
    }
}