我有问题。我想获得一个元素的属性。 我的问题的线索是,所有元素都有相同的名称。
XML-Data的外观
<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指定的正确元素来获取属性。
答案 0 :(得分:0)
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));
答案 1 :(得分:0)
你可以尝试这样的事情。
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();
答案 2 :(得分:0)
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;
}
}