获取xml数据的属性(wpf c#)
本文关键字:wpf 属性 xml 数据 获取 | 更新日期: 2023-09-27 18:27:19
我有个问题。我想要得到一个元素的属性。我的问题的线索是,所有元素都有相同的名称。
XML数据的外观
<Sampels>
<Sampel Attribute1="a" Attribute2="b" Attribute3="3" Attribute4="d" />
<Sampel Attribute1="asdf" Attribute2="b" Attribute3="3" Attribute4="name" />
<Sampel Attribute1="" Attribute2="" Attribute3="66" Attribute4="attri" />
<Sampel Attribute1="" Attribute2="b" Attribute3="" Attribute4="sampelname" />
</Sampels>
我想通过知道从Attribute4中指定的正确元素来获得属性。
XPath将执行以下操作:
使用这些包括:
using System.Xml.Linq;
using System.Xml.XPath;
并找到您的属性值(xml是您的xml字符串):
string search = "sampelname";
XDocument doc = XDocument.Parse(xml);
XElement el = doc.XPathSelectElement(string.Format("/Sampels/Sampel[@Attribute4='{0}']", search));
您可以尝试这样的方法。
XElement xmlElement = XElement.Load("myFile.xml");
var attributes = (from e in xmlElement.Elements("Sample")
where e.Attribute("Attribute4").Value == "myAtribute4Value"
select new {
Attribute1 = e.Attribute("Attribute1").Value,
Attribute2 = e.Attribute("Attribute2").Value
}).FirstOrDefault();
static void Main(string[] main)
{
var samples = @"<Sampels>
<Sampel Attribute1='a' Attribute2='b' Attribute3='3' Attribute4='d' />
<Sampel Attribute1='asdf' Attribute2='b' Attribute3='3' Attribute4='name' />
<Sampel Attribute1='' Attribute2='' Attribute3='66' Attribute4='attri' />
<Sampel Attribute1='' Attribute2='b' Attribute3='' Attribute4='sampelname' />
</Sampels>";
dynamic Sampels = DynamicXml.Parse(samples);
foreach(var sample1 in Sampels.Sampel)
{
Console.WriteLine(sample1.Attribute4);
}
}
// using http://stackoverflow.com/questions/13704752/deserialize-xml-to-object-using-dynamic
public class DynamicXml : System.Dynamic.DynamicObject
{
XElement _root;
private DynamicXml(XElement root)
{
_root = root;
}
public static DynamicXml Parse(string xmlString)
{
return new DynamicXml(XDocument.Parse(xmlString).Root);
}
public static DynamicXml Load(string filename)
{
return new DynamicXml(XDocument.Load(filename).Root);
}
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
result = null;
var att = _root.Attribute(binder.Name);
if (att != null)
{
result = att.Value;
return true;
}
var nodes = _root.Elements(binder.Name);
if (nodes.Count() > 1)
{
result = nodes.Select(n => new DynamicXml(n)).ToList();
return true;
}
var node = _root.Element(binder.Name);
if (node != null)
{
if (node.HasElements)
{
result = new DynamicXml(node);
}
else
{
result = node.Value;
}
return true;
}
return true;
}
}