我有代码(可以工作),它将循环遍历一系列XML元素(Id),当它找到元素值和预定义变量(cpluuid)之间的匹配时,它将更新另一个子元素元素值(OriginalFileName),基于预定义的函数(SetNewValue)。
我无法弄清楚的是,如果它已经通过所有元素循环而没有找到匹配,那么如何抛出错误仅。理想情况下,它还将停止执行程序中的其余代码。
我可以在找到每个不匹配的元素时抛出错误,但这不是我想要的。
XML示例:
<PackingList xmlns="http://www.smpte-ra.org/schemas/2067-2/2016/PKL">
<Id>urn:uuid:296a656c-3610-4de1-9b08-2aa63245788d</Id>
<AnnotationText>IMF_JOT_Sample</AnnotationText>
<IssueDate>2018-02-16T20:59:42-00:00</IssueDate>
<Issuer>Generic</Issuer>
<Creator>Generic</Creator>
<AssetList>
<Asset>
<Id>urn:uuid:dd5a88d2-ccec-4b22-8584-fda51945c3ea</Id>
<AnnotationText>Audio_dd5a88d2-ccec-4b22-8584-fda51945c3ea.mxf</AnnotationText>
<Hash>OwjRFnWZCdKHSZ+3PBXroDhMMlY=</Hash>
<Size>1458414</Size>
<Type>application/mxf</Type>
<OriginalFileName>Audio_dd5a88d2-ccec-4b22-8584-fda51945c3ea.mxf</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
</Asset>
<Asset>
<Id>urn:uuid:9e11458a-71fb-4702-8609-55d2308dcc64</Id>
<AnnotationText>Sub_9e11458a-71fb-4702-8609-55d2308dcc64.mxf</AnnotationText>
<Hash>48KyxgwCJVXIdgAGfaNApheQN5M=</Hash>
<Size>34509</Size>
<Type>application/mxf</Type>
<OriginalFileName>Sub_9e11458a-71fb-4702-8609-55d2308dcc64.mxf</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
</Asset>
<Asset>
<Id>urn:uuid:d0686356-19c7-4bf4-b915-db778c308d1</Id>
<AnnotationText>CPL_IMF_JOT_Sample.xml</AnnotationText>
<Hash>5Yf4BV4GZ4qE9EjvtohZ8Rq8M2w=</Hash>
<Size>21881</Size>
<Type>text/xml</Type>
<OriginalFileName>CPL_IMF_JOT_Sample_272.xml</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
</Asset>
<Asset>
<Id>urn:uuid:3f57f474-4c81-438e-a67d-1b08fa09a10d</Id>
<AnnotationText>IMF_JOT_Sample</AnnotationText>
<Hash>q8TiPkg/3devlN3LXnBhrgkZ968=</Hash>
<Size>713</Size>
<Type>text/xml</Type>
<OriginalFileName>OPL_3f57f474-4c81-438e-a67d-1b08fa09a10d.xml</OriginalFileName>
<HashAlgorithm Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
</Asset>
</AssetList>
</PackingList>
代码:
foreach (var pklasset in pklassetElements)
{
var idElement = pklasset.Descendants(pklns + "Id").First();
if (!idElement.Value.Equals(cpluuid))
continue;
SetNewValue(pklasset, pklns + "OriginalFileName", outfile);//update cpl filename in pkl
}
答案 0 :(得分:0)
一种方法是设置bool
标志变量以跟踪您是否找到匹配项:
bool foundItem = false;
foreach (var pklasset in pklassetElements)
{
var idElement = pklasset.Descendants(pklns + "Id").First();
if (!idElement.Value.Equals(cpluuid)) continue;
//update cpl filename in pkl
SetNewValue(pklasset, pklns + "OriginalFileName", outfile);
foundItem = true;
break;
}
if (!foundItem) throw new Exception("Item not found");