c# - 有没有更好的方法来访问我的 XML 文档中的子节点?
问题描述
这是我的 XmlDocument
<?xml version="1.0"?>
<Config>
<Path1></Path1>
<Path2></Path2>
<Path3></Path3>
<Path4></Path4>
<Path5></Path5>
<PdfMenu>
<PdfDocument Attribute1="1" Attribute2="1.1" Attribute3="1.2" Attribute4="1.3" Attribute5="1.4" />
<PdfDocument Attribute1="2" Attribute2="2.1" Attribute3="2.2" Attribute4="2.3" Attribute5="2.4" />
<PdfDocument Attribute1="3" Attribute2="3.1" Attribute3="3.2" Attribute4="3.3" Attribute5="3.4" />
</PdfMenu>
</Config>
我目前正在使用它来解决节点<PdfMenu>
foreach (XmlNode n in xmlDoc.ChildNodes.Item(1).ChildNodes.Item(5).ChildNodes)
现在,每次我添加另一个时,<Path>
我都必须调整Item
数字。有没有更好的方法来做到这一点?
解决方案
最好使用 LINQ to XML API。它在 .Net 框架中可用超过 10 年。
Descendants()
无论 XML 中有多少其他元素,该方法都会直接访问您需要的元素。
C#
void Main()
{
XDocument xdoc = XDocument.Parse(@"<Config>
<Path1></Path1>
<Path2></Path2>
<Path3></Path3>
<Path4></Path4>
<Path5></Path5>
<PdfMenu>
<PdfDocument Attribute1='1' Attribute2='1.1' Attribute3='1.2'
Attribute4='1.3' Attribute5='1.4'/>
<PdfDocument Attribute1='2' Attribute2='2.1' Attribute3='2.2'
Attribute4='2.3' Attribute5='2.4'/>
<PdfDocument Attribute1='3' Attribute2='3.1' Attribute3='3.2'
Attribute4='3.3' Attribute5='3.4'/>
</PdfMenu>
</Config>");
foreach (var element in xdoc.Descendants("PdfDocument"))
{
Console.WriteLine(element);
}
}
推荐阅读
- python - 带有 pep8 命名的 Flake8 抱怨 camelCase 进口
- xamarin.forms - 为什么我的 Azure SignalR Hub 方法没有被触发?
- r - 如何计算不同变量的每个个体的平均值
- python - 使用 python 导入 GCP 资源时出现凭据错误
- pandas - 将源表作为 Pandas 数据框的 Snowflake MERGE 命令
- ms-access - 无法访问查询对象的 SQL 视图
- openai-gym - 是否可以保存用于安全健身房模拟的视频?
- keras - Tensorflowjs:如何判断keras模型转换成什么格式
- jquery - 如何从使用 Bootstrap 文件输入选择的文件中获取 Base64 字符串并使用 AJAX 提交字符串?
- python - Flask Sqlalchmey - Marshmallow Nested Schema 对于带有过滤器( where )条件的连接失败