嗨我得到了下面的xml
<InstanceData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<letter>
<variableBlocks>
<VariableBlockBase xsi:type="ClientVariableBlock">
<FirstName></FirstName>
<LastName></LastName>
<Address></Address>
</VariableBlockBase>
<VariableBlockBase xsi:type="PaymentVariableBlock">
<LastPaymentDate></LastPaymentDate>
<LastPaymentAmount></LastPaymentAmount>
<Address></Address> <!-- repeated (Address appear in the VariableBlockBase above) so this xml should be invalid -->
</VariableBlockBase>
</variableBlocks>
</letter>
</InstanceData>
正在构建xml 动态。
每个<VariableBlockBase>
都有一个或多个变量(FirstName,Address等)
我想查看2个约束
<VariableBlockBase>
<VariableBlockBase>
在示例xml中,看到<Address>
个实例(客户端和付款)中出现<VariableBlockBase>
我想创建一个Linq查询来获取重复标记的列表。我在XmlDocument实例中得到了这个xml。
答案 0 :(得分:1)
我不确定将所有代码放在一个linq查询中,但这里是非linq解决方案:
string xml = @"<InstanceData xmlns:xsi=""http://www.w3.org/2001/XMLSchema-
instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<letter>
<variableBlocks>
<VariableBlockBase xsi:type=""ClientVariableBlock"">
<FirstName></FirstName>
<LastName></LastName>
<Address></Address>
</VariableBlockBase>
<VariableBlockBase xsi:type=""PaymentVariableBlock"">
<LastPaymentDate></LastPaymentDate>
<LastPaymentAmount></LastPaymentAmount>
<Address></Address> <!-- repeated (Address appear in the VariableBlockBase above) so this xml should be invalid -->
</VariableBlockBase>
</variableBlocks>
</letter>
</InstanceData>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList allElements = doc.SelectNodes("//VariableBlockBase/*");
foreach(XmlElement childNode in doc.SelectNodes("InstanceData/letter/variableBlocks/*"))
{
foreach ( XmlElement grandChildNode in childNode.ChildNodes )
{
try
{
allElements.Cast<XmlElement>().SingleOrDefault(x => x.Name == grandChildNode.Name);
}
catch ( InvalidOperationException )
{
throw new Exception("The tag <" + grandChildNode.Name + "> has been found more than once");
}
catch
{
throw;
}
}
}