【问题标题】:How to take value based on previous node from the given xml file如何根据给定 xml 文件中的前一个节点获取值
【发布时间】:2017-09-30 19:02:17
【问题描述】:

我有一个如下所示的 xml 文件,它是大 xml 文件的一小部分

<?xml version="1.0" encoding="utf-8" ?>
<xn:VsDataContainer id=test">
  <xn:attributes>
    <xn:vsDataType>vsDataEUtranCellFDD</xn:vsDataType>
    <es:crsGain>0</es:crsGain>
    <es:pciConflictCell>
      <es:enbId>66111</es:enbId>
      <es:cellId>3</es:cellId>
    </es:pciConflictCell>
    <es:pdcchLaGinrMargin>100</es:pdcchLaGinrMargin>
    <es:lbEUtranAcceptOffloadThreshold>50</es:lbEUtranAcceptOffloadThreshold>
    <es:pdcchCfiMode>5</es:pdcchCfiMode>
    <es:cellId>0</es:cellId>
    <es:zzzTemporary21>-2000000000</es:zzzTemporary21>
  </xn:attributes>
</xn:VsDataContainer>

我正在使用以下代码来获取crsGaincellId 的值。但是cellIdiam 没有得到想要的值。即如果前一个节点是pdcchCfiMode,我需要cellId。所以在这里我应该将值设为 0,但我得到 3,这是序列中的第一个。如何解决这个问题。我使用的代码片段是

if (vsDataEUtranCellFDD.Any()) {
    List<CellName> cells = vsDataEUtranCellFDD.Select(x => new CellName() {
        cellId= (int)x.Descendants().Where(a => a.Name.LocalName == "cellId").FirstOrDefault(),
        crsGain = (int)x.Descendants().Where(a => a.Name.LocalName == "crsGain").FirstOrDefault(),

编辑

这个cellid也可以发生在中间,唯一的区别是前一个节点是pdcchCfiMode

【问题讨论】:

  • 这个cellid也可以发生在中间,唯一的区别是前一个节点是pdcchCfiMode
  • 你能保证每次pdcchCfiMode之后,cellid总是发生吗?
  • 是的 100% 保证
  • 好的。检查我的答案。希望对您有所帮助。

标签: c# xml linq linq-to-xml


【解决方案1】:

你可以skip the elements while他们不等于pdcchCfiMode然后取第一个元素。像这样的:

cellId = (int)x.Descendants().SkipWhile(a => a.Name.LocalName != "pdcchCfiMode")
        .Skip(1).Take(1).FirstOrDefault(),

【讨论】:

    【解决方案2】:

    试试下面的代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                List<XElement> attributes = doc.Descendants().Where(x => x.Name.LocalName == "attributes").ToList();
    
                XNamespace esNs = attributes.FirstOrDefault().GetNamespaceOfPrefix("es");
    
                List<CellName> cells = attributes.Select(x => new CellName() {
                    cellId = (int)x.Element(esNs + "cellId"),
                    crsGain = (int)x.Element(esNs + "crsGain")
                }).ToList();
            }
        }
        public class CellName
        {
            public int cellId { get; set; }
            public int crsGain { get; set; }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 2014-01-05
      • 2012-05-30
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多