c# - 从不同的父元素中提取某些 XML 元素值
问题描述
我有一个 XML 文件,其中包含 10 个 Mesh 节点,每个节点都包含 Vertex 和 Face 元素。基本上对于每个网格节点,我需要创建一个:
- 包含所有顶点的新列表(vector3 类型)
- 包含所有面孔的新列表(vector3 类型)
- 保存网格 ID(字符串类型)
我对使用什么语句进行这种动态信息分析和提取感到困惑。下面是一些简化的 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;
}
解决方案
问题是使用列表索引器尝试添加新值。您可以验证这不起作用,而无需担心 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();
推荐阅读
- jquery - 过滤器上容器外的同位素项目
- java - 无法将字符串添加到数据库:BaseXException:名称“”无效
- mysql - SQL 查询以获取 ID 的计数值,其中 ID 计数 > 1 为按月分组的最后 14 个尾随月份
- python - 如何将 pdf 文档从 Azure Studio 发送到 S3 存储桶
- laravel - Laradock - SQLSTATE [HY000] [2002] 连接被拒绝(SQL:从 `users` 中选择 count(*) 作为聚合,其中 `email` =
- javascript - 如何为暗/亮模式切换保存 cookie?
- json - 使用 json 向多个收件人发送邮件
- r - 是否有一个 R 包可以加速时间序列分析中的滞后和差分?
- php - 如何从 URI 中获取正则表达式,如 Laravel 路由
- html - 如何在手机/标签等中自动旋转网页游戏