2016-09-26 39 views
0

单一的XElement我有一个结构类似这样的XML文件:无法从XML

<scan client="Computer1" end="9/20/2016 7:00:00 AM" start="9/20/2016 7:00:00 AM"> 
    <childfile> 
    <name>file.ext</name> 
    <lastmodified>8/31/2016</lastmodified> 
    <age>19</age> 
    </childfile> 
    <childfile> 
    <name>file2.ext</name> 
    <lastmodified>9/1/2016</lastmodified> 
    <age>18</age> 
    </childfile> 
    <childfile> 
    <name>file3.ext</name> 
    <lastmodified>8/19/2016</lastmodified> 
    <age>31</age> 
    </childfile> 
    <childfile> 
    <name>file4.ext</name> 
    <lastmodified>8/23/2016</lastmodified> 
    <age>27</age> 
    </childfile> 
</scan> 
<scan client="Computer2" end="9/20/2016 7:00:00 AM" start="9/20/2016 7:00:00 AM"> 
    <childfile> 
    <name>file.ext</name> 
    <lastmodified>8/31/2016</lastmodified> 
    <age>19</age> 
    </childfile> 
    <childfile> 
    <name>file2.ext</name> 
    <lastmodified>9/1/2016</lastmodified> 
    <age>18</age> 
    </childfile> 
    <childfile> 
    <name>file3.ext</name> 
    <lastmodified>8/19/2016</lastmodified> 
    <age>31</age> 
    </childfile> 
    <childfile> 
    <name>file4.ext</name> 
    <lastmodified>8/23/2016</lastmodified> 
    <age>27</age> 
    </childfile> 
</scan> 

我送那个看起来像上面一个新的XML元素,它会是这样的:

<scan client="Computer1" end="9/25/2016 7:00:00 AM" start="9/25/2016 7:00:00 AM"> 
    <childfile> 
    <name>file.ext</name> 
    <lastmodified>8/31/2016</lastmodified> 
    <age>19</age> 
    </childfile> 
    <childfile> 
    <name>file2.ext</name> 
    <lastmodified>9/1/2016</lastmodified> 
    <age>18</age> 
    </childfile> 
</scan> 

如何搜索原始XML以查看其扫描部分是否具有与所提供的客户端属性相匹配的客户端属性,如果匹配,请用提供的客户端属性替换该元素。如果找不到匹配项,则只需将该元素添加到现有元素中即可。

我尝试使用:

originalXML.Elements("scan").SingleOrDefault(e => e.Attribute("client").Value == client) 

在客户端VAR使用

string client = replacementXML.Attribute("client").Value; 

好像它设置为null每次回来,即使我检查了客户端字符串,并将其设置到“Computer1”。

有关为什么总是返回null的任何想法?

+0

如果您尝试'originalXML.Root.Elements(“scan”)...' – Jonesopolis

+2

会发生什么情况您的xml格式不正确(xml只能有一个根元素),或者您没有显示整个xml结构。这使我们很难确定如何访问特定元素。 – Kevin

+0

@Jonesopolis如果我将它更改为originalXML.Root.Elements ....它仍然返回null。 – Vladmere

回答

0

你有两个问题...

  1. XML格式不正确 - 你必须有一个根元素
  2. 你需要引用你的“SCAN”元素把你的根对象

所以你linq2xml看起来像这样...

var client = replacementXML.Root.Attribute("client").Value; 
var match = originalXML.Root.Elements("scan") 
     .SingleOrDefault(e => e.Attribute("client").Value == client); 

好吧我想我有点晚了..我看到你r评论说你已经修复了。 :)