c# - 如何根据C#中的另一个属性值获取XML节点的属性值
问题描述
这是 XML:
<MatML_Doc>
<Material>
<BulkDetails>
<Name>ABS</Name>
<Class> <Name>PLASTIC</Name></Class>
<Subclass> <Name>ABS Polymer</Name></Subclass>
<PropertyData property="Material_Type">
<Data format="string">IsotropicMaterial</Data>
</PropertyData>
<PropertyData property="Version">
<Data format="string">4.0</Data>
</PropertyData>
<PropertyData property="Category">
<Data format="string">PLASTIC</Data>
</PropertyData>
<PropertyData property="CoatingsStudioMaterialName">
<Data format="string">ABS Plastic</Data>
</PropertyData>
<PropertyData property="CoatingsVisualizationColor">
<Data format="exponential">168, 168, 168</Data>
</PropertyData>
<PropertyData property="ColorID">
<Data format="integer">87</Data>
</PropertyData>
</BulkDetails>
</Material>
<MatML_Doc>
如果节点“Name”的值为 ABS,我想获取数据属性“ColorID”的值(我想要数字 87)。通常的程序是什么?
我在这里添加我的解决方案:
private static int GetColorIdInXmlByMaterial(string material, XmlDocument doc)
{
XmlElement element = doc.DocumentElement;
XmlNodeList xmlNodeList = element.SelectNodes("//BulkDetails");
foreach(XmlNode node in xmlNodeList)
{
if (node["Name"].InnerText.Equals(material))
{
return Convert.ToInt32(node["ColorID"].InnerText);
}
}
return 0;
}
解决方案
使用 xml linq :
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<Material> meterials = doc.Descendants("Material").Select(x => new Material()
{
name = (string)x.Descendants("Name").FirstOrDefault(),
className = (string)x.Descendants("Class").FirstOrDefault().Element("Name"),
properties = x.Descendants("PropertyData").Select(y => new Property()
{
property = (string)y.Attribute("property"),
format = (string)y.Element("Data").Attribute("format"),
value = (string)y.Element("Data")
}).ToList()
}).ToList();
Dictionary<string, Material> dict = materials.GroupBy(x => x.name, y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
Material lookup = dict["ABS"];
}
}
public class Material
{
public string name { get; set; }
public string className { get; set; }
public List<Property> properties { get; set; }
}
public class Property
{
public string property { get; set; }
public string format { get; set; }
public string value { get; set; }
}
}
推荐阅读
- java - 按对象之一对数组列表中的对象进行排序
- python - “ImportError:无法从 PyQt5 导入名称 QtCore”或任何其他模块
- extjs - 如何使用 .remove() EXTJS 删除 2 个容器
- sql - 在 where 子句 oracle 中切换大小写
- python - Python:如何在图中获得更平滑的起点?
- javascript - 试图从 WKWebView 中的 Javascript 获取信息(使用 KINWebBrowser)
- python - 如何同时写入多个 TCP 套接字?
- php - 如何提交切换数据以通过 Ajax 在我的 mysql 中更改布尔值的状态?
- mongodb - 无法将类型“PersistEntityBackend a0”与“MongoContext”匹配——通过 ObjectId 获取文档
- java - 在 Java 中不使用 XSLT 将 XML 属性转换为标签(节点)