在if语句中检查相同类型的最后一项的更好方法

问题描述 投票:0回答:1

我已经编写了读取.xml文件并将其元素写入新文件的代码。这段代码效果很好,但我想考虑其他可能的改进。

旧文档的结构是:

<rootElement>
     <firstType>someValue</firstType>
     ...
     <firstType>someValue</firstType>
     <secondType Attr1="value" Attr2="value" Attr3="value" Attr4="value">someValue</firstType>
     <thirdType>someValue</firstType>
</rootElement>

新的.xml必须看起来像:

<rootElement>
     <firstType>someValue</firstType>
     ...
     <firstType>someValue</firstType>
     <secondType Attr1="value" Attr2="value" Attr3="value" Attr4="value">someValue</firstType>
</rootElement>

请注意它没有''的新结构。

因此,有很多“ firstType”元素,后跟两个相应的元素“ secondType”和“ thirdType”。我需要检查foreach迭代的当前XElement是否为最后一个“ firstType”元素。如果该语句为真,请执行一些操作:

if ((hour.NextNode == hisDoc.Root.XPathSelectElement("secondType")) || (hour.NextNode == hisDoc.Root.XPathSelectElement("thirdType"))){
     if ((hisDoc.Element("newRoot").Element("secondType") != null) && (fcsDay.XPathSelectElement("secondType") == null)) {
          fcsDay.Add(new XElement("secondType",
               new XAttribute("Attr1", hisDoc.Root.XPathSelectElement("secondType").Attribute("Attr1").Value),
               new XAttribute("Attr2", hisDoc.Root.XPathSelectElement("secondType").Attribute("Attr2").Value),
               new XAttribute("Attr3", hisDoc.Root.XPathSelectElement("secondType").Attribute("Attr3").Value),
               new XAttribute("Attr4", hisDoc.Root.XPathSelectElement("secondType").Attribute("Attr4").Value)));
     }
}
fcsDoc.Save(FCSfileName); 

我已经完成了任务,尽管可能会有所增强。我的意思是是否添加了更多其他元素,例如'fourthType'。较长的if语句将不方便。我使用LINQtoXML(XDocument),但由于速度较慢,所以不想更改为XmlDocument。而且,XDocument更易于使用。

我认为这必须是执行该任务的更有效方法。

c# xml linq if-statement linq-to-xml
1个回答
0
投票

例如,您可以简单地使用!=运算符呢?

if(first.NextNode != hisDoc.Root.XPathSelectElement("firstType"))
© www.soinside.com 2019 - 2024. All rights reserved.