首页 > 解决方案 > 从不同的父元素中提取某些 XML 元素值

问题描述

我有一个 XML 文件,其中包含 10 个 Mesh 节点,每个节点都包含 Vertex 和 Face 元素。基本上对于每个网格节点,我需要创建一个:

我对使用什么语句进行这种动态信息分析和提取感到困惑。下面是一些简化的 XML 代码用于说明。

<Mesh id="Cube">
  <Vertex position="0.9823, 2.3545, 30.251" />
  <Vertex position="-0.0177, 2.3545, 30.251" />
  <Vertex position="0.9823, 3.3545, 30.251" />
  <Vertex position="-0.0177, 3.3545, 30.251" />
  <Face vertices="0, 2, 3" />
  <Face vertices="0, 3, 1" />

<Mesh id="Wall">
  <Vertex position="-4.9048, -1.0443, -4.8548" />
  <Vertex position="-5.404, -1.018, -4.8636" />
  <Vertex position="-4.6416, 3.9487, -4.8548" />
  <Vertex position="-5.1409, 3.975, -4.8636" />
  <Face vertices="0, 2, 3" />
  <Face vertices="0, 3, 1" />

我当前的解决方案返回“参数超出范围”。我不确定如何将 Vertices 列表转换为 Vector3 列表以及如何首先检索网格 ID。

XDocument xml = XDocument.Load("C:\\Users\\Test.xml");
List<string> Vertices= new List<string>();
int i = 0;

IEnumerable<XElement> de =
    from element in xml.Descendants("Vertex")
    select element;
foreach (XElement element in de)
{
    Vertices[i] = element.Attribute("position").Value;
    i += 1;
}

标签: c#xml

解决方案


问题是使用列表索引器尝试添加新值。您可以验证这不起作用,而无需担心 XML:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        var list = new List<string>();
        list[0] = "test"; // Bang: ArgumentOutOfRangeException
    }
}

幸运的是,您根本不需要它 - 您的代码可以更正并简化为:

XDocument xml = XDocument.Load("C:\\Users\\Test.xml");
List<string> vertices = xml
    .Descendants("Vertex")
    .Select(x => x.Attribute("position").Value)
    .ToList();

推荐阅读