我想从每个“临时”产品的所有详细信息标签中选择“最高”的深度、宽度和高度值。
这是我的 XML 示例:
<root>
<Temp>
<Code>1234567</Code>
<Detail>
<Depth>12.7</Depth>
<Width>1.27</Width>
<Height>15.24</Height>
</Detail>
<DetailConversion>
<Detail>
<Depth>34.925</Depth>
<Width>30.48</Width>
<Height>19.05</Height>
</Detail>
</DetailConversion>
<DetailConversion>
<Detail>
<Depth>34.925</Depth>
<Width>30.48</Width>
<Height>19.05</Height>
</Detail>
</DetailConversion>
</Temp>
<Temp>
<Code>1234567</Code>
<Detail>
<Depth>12.7</Depth>
<Width>1.27</Width>
<Height>15.24</Height>
</Detail>
<DetailConversion>
<Detail>
<Depth>34.925</Depth>
<Width>30.48</Width>
<Height>19.05</Height>
</Detail>
</DetailConversion>
<DetailConversion>
<Detail>
<Depth>34.925</Depth>
<Width>30.48</Width>
<Height>19.05</Height>
</Detail>
</DetailConversion>
</Temp>
</root>
我试过了
int maxDepth = doc.Root.Elements().Max(x => (int)x.Element("Depth"));
int maxWidth = doc.Root.Elements().Max(x => (int)x.Element("Width"));
int maxHeight = doc.Root.Elements().Max(x => (int)x.Element("Height"));
但我真的不知道为什么这不起作用,maxDepth 始终为 0。 maxDepth...必须为每个选择,而不是一起选择
你有什么想法吗?
更新完整的 XML
<?xml version="1.0" encoding="utf-8"?>
<XmlInterchange xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.edi.com.au/EnterpriseService/" Version="1" >
<InterchangeInfo>
<Date>2015-05-29T14:17:45</Date>
</InterchangeInfo>
<Payload>
<Temporaer>
<Temp>
<TempCode>ST66676EU</TempCode>
<DetailConversion>
<Depth>12.7</Depth>
<Width>1.27</Width>
<Height>15.24</Height>
</DetailConversion>
<DetailConversions>
<DetailConversion>
<Depth>16.51</Depth>
<Width>13.97</Width>
<Height>6.35</Height>
</DetailConversion>
<DetailConversion>
<Depth>34.925</Depth>
<Width>30.48</Width>
<Height>19.05</Height>
</DetailConversion>
</DetailConversions>
</Temp>
</Temporaer>
</Payload>
</XmlInterchange>
最佳答案
您必须使用 Descendant()
获取根的所有子节点,因为 Elements()
不会获取嵌套的子节点:
int maxDepth = doc.Root.Descendants().Max(x => (int)x.Element("Depth"));
或更准确地说是:
int maxDepth = doc.Root.Descendants("Detail").Max(x => (int)x.Element("Depth")));
更新:
你想获得每个Temp
节点的max Depth元素值,那么你必须这样做:
var maxDepth = doc.Root.Descendants("Detail")
.Select(x=>x.Max(y => (int)y.Element("Depth")));
或:
var maxDepth = doc.Root.Descendants("Temp")
.Select(x=>x.Descendants("Detail"))
.Select(x=>x.Max(y => (int)y.Element("Depth")));
关于c# - 选择节点值并选择最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30638212/