C# 获取xml数据的属性(wpf c)
我有个问题。我想得到一个元素的属性。 我的问题的线索是,所有元素都有相同的名称 XML数据的外观C# 获取xml数据的属性(wpf c),c#,wpf,C#,Wpf,我有个问题。我想得到一个元素的属性。 我的问题的线索是,所有元素都有相同的名称 XML数据的外观 <Sampels> <Sampel Attribute1="a" Attribute2="b" Attribute3="3" Attribute4="d" /> <Sampel Attribute1="asdf" Attribute2="b" Attribute3="3" Attribute4="name" /> <Sampel Attribut
<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();
你应该看看,看看。还有很多其他的解决方案,关于Stackoverflow,您可能应该在发布问题之前先搜索。他们使用childenotes,但我不这样做,所以这两个问题不相等。如果没有被提取,您也可以修改以提取属性。我喜欢这里的解决方案的原因是,它允许您在sample var attribute4=sample1.attribute4中执行foreachvar sample1之类的操作
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;
}
}