C# 获取存储在给定类型的一组属性中的值
我有以下XML文件,如何获得存储在给定类型的标记中的值(在本例中是FileModel类型的标记) .. 我如何编写一些代码来获得Rep1和Rep2的值。我需要这些值来在方法中运行某种验证 我怎样才能做到这一点C# 获取存储在给定类型的一组属性中的值,c#,xml,serialization,C#,Xml,Serialization,我有以下XML文件,如何获得存储在给定类型的标记中的值(在本例中是FileModel类型的标记) .. 我如何编写一些代码来获得Rep1和Rep2的值。我需要这些值来在方法中运行某种验证 我怎样才能做到这一点 <?xml version="1.0"?> <MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<?xml version="1.0"?>
<MainClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<Settings xsi:type="FileModel">
<Name>Rep1</Name>
<IsActive>true</IsActive>
<IsHidden>false</IsHidden>
</Settings>
<Settings xsi:type="FileModel">
<Name>Rep2</Name>
<IsActive>true</IsActive>
<IsHidden>false</IsHidden>
</Settings>
<Settings xsi:type="ServerModel">
<Name>DelRep</Name>
<IsActive>false</IsActive>
<IsHidden>false</IsHidden>
</Settings>
</Items>
</MainClass>
您可以使用XPath和XmlNamespaceManager来实现这一点
例如:
使用制度;
使用System.Linq;
使用System.Xml;
使用System.Xml.Linq;
使用System.Xml.XPath;
公共课程
{
公共静态真空总管
{
var doc=XDocument.ParseXmlString;
var namespaceManager=新的XmlNamespaceManagernew NameTable;
namespaceManager.AddNamespacexsi,http://www.w3.org/2001/XMLSchema-instance;
var name=doc.XPathSelectElements
/MainClass/Items/Settings[@xsi:type='FileModel']/Name,
名称空间管理器
.选择e=>e.值;
Console.WriteLineString.Join,名称;
}
私有静态字符串XmlString=@
报告1
符合事实的
错误的
报告2
符合事实的
错误的
德勒普
错误的
错误的
;
}
如果要使用System.Xml,将输出:Rep1、Rep2:
您可以使用LINQtoXML来实现所需的结果。这比你想象的要简单。您不需要完全了解xml或linq 要检索设置中的所有名称,类型等于FileModel的节点 代码: 输出: 或者,如果您希望结果是单个字符串,则可以用逗号连接上面的列表,如 输出:
您目前是如何处理XML的?通过XmlSerializer反序列化?使用LINQ解析为XML?使用XmlDocument解析?现在,我的整个XML文件存储为字符串,类似于字符串wholeContent=file.ReadAllTextthis.FilePath;整个内容都在其他地方使用,但我认为LINQtoXML在本文中是一种更好的方法检查其他答案,看看是否有什么可以帮助您
static void Main(string[] args)
{
List<string> result = new List<string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("myfile.xml");
XmlNodeList elemList = xmlDoc.GetElementsByTagName("Settings");
foreach (XmlNode node in elemList)
{
if(node.Attributes["xsi:type"].Value == "FileModel")
{
foreach (XmlNode item in node.ChildNodes)
{
if (item.Name == "Name")
result.Add(item.InnerText);
}
}
}
}
var doc = XDocument.Load("Path to xml file");
//Or
var doc = XDocument.Parse(XmlString);
var ns = doc.Root.GetNamespaceOfPrefix("xsi");
var names = doc.Descendants("Items")
.Elements("Settings")
.Where(x => x.Attribute(ns + "type").Value == "FileModel")
.Select(x => x.Element("Name").Value)
.ToList();
names.ForEach(x => Console.WriteLine(x));
var allName = string.Join(", ", names);
Console.WriteLine(allName);