在 C# 中使用 xdocument 获取父节点值很热门吗?

Hot to get parent node value using xdocument in c#?

我在 .Net 中创建 MVC 应用程序,当我使用 xdocument 访问 WCF 服务时,我在获取父节点的值时遇到问题。如何做到这一点?

如果你知道父节点的名称,你可以按照我的例子。使用您的节点名称代替我的 _Region.

我的 xml:

<?xml version="1.0" encoding="UTF-8"?>
<_Document_Definition>
    <_Regions>
        <_Region>
            <_Name>regionStaticTextTerminDii</_Name>
            <_Coordinates>
                <_X1>241</_X1>
                <_Y1>166</_Y1>
                <_X2>683</_X2>
                <_Y2>197</_Y2>
            </_Coordinates>
            <_BlockTypeEnum>BT_StaticText</_BlockTypeEnum>  
        </_Region>
        <_Region>
            <_Name>regionStaticTextExtension</_Name>
            <_Coordinates>
                <_X1>238</_X1>
                <_Y1>198</_Y1>
                <_X2>538</_X2>
                <_Y2>232</_Y2>
            </_Coordinates>
            <_BlockTypeEnum>BT_StaticText</_BlockTypeEnum>  
        </_Region>
    </_Regions>
</_Document_Definition>

接下来我做:

XDocument xDoc = XDocument.Load(docDifPath);
var infoRegions = from x in xDoc.Descendants("_Region")
                    select new
                    {
                        Name = x.Descendants("_Name").First().Value,
                        X1 = x.Descendants("_X1").First().Value,
                        Y1 = x.Descendants("_Y1").First().Value,
                        X2 = x.Descendants("_X2").First().Value,
                        Y2 = x.Descendants("_Y2").First().Value,
                        BlockTypeEnum = x.Descendants("_BlockTypeEnum").First().Value
                    };
//using obtaining info. I created Region class before
List<Region> regions = new List<Region>();
foreach (var i in infoRegions)
{
    Region region = new Region();
    region.name = i.Name;
    region.x1 = Convert.ToInt32(i.X1);
    region.y1 = Convert.ToInt32(i.Y1);
    region.x2 = Convert.ToInt32(i.X2);
    region.y2 = Convert.ToInt32(i.Y2);
    region.blockTypeEnumElem = (BlockTypeEnum)Enum.Parse(typeof(BlockTypeEnum), i.BlockTypeEnum);
    regions.Add(region);
}