n下面的xml,
<?xml version="1.0" encoding="utf-8"?>
<Models>
<Model DESC="HONDA-BLUE-450" MODELID="XX12-01" Status="in" />
<Model DESC="VOLKS--RED-345" MODELID="XY12-01" Status="in" />
<Model DESC="BENZ-BLUE-550" MODELID="XX12-01" Status="in" />
<Model DESC="VOLKS--CYAN-345" MODELID="BG12-01" Status="out" />
<Model DESC="HONDA-GREEN-234" MODELID="AX12-01" Status="in" />
<Model DESC="VOLKS-Yellow-765" MODELID="XY11-01" Status="in" />
<Model DESC="HONDA-GREEN-109" MODELID="AC12-01" Status="in" />
<Model DESC="AUDI-GREEN-984" MODELID="AF42-01" Status="in" />
<Model DESC="VOLKS-Yellow-565" MODELID="XJ11-61" Status="out" />
<Model DESC="HONDA-WHITE-079" MODELID="DC12-38" Status="in" />
<Model DESC="TOYOTA-GREY-109" MODELID="UC12-81" Status="in" />
<Model DESC="AUDI-CYAN-984" MODELID="LF42-41" Status="in" />
<Model DESC="VOLKS-WHITE-865" MODELID="LK11-61" Status="out" />
<Model DESC="HONDA-GREY-039" MODELID="PC12-31" Status="in" />
</Models>
我想得到状态为out的所有MODELID值,DESC以VOLKS开头。任何帮助将不胜感激。
答案 0 :(得分:1)
您可以使用linq to xml遍历xml节点和String.StartsWith
以检查atttribute DESC
值是否以“VOLKS”开头:
XDocument xdoc = XDocument.Load("data.xml");
var modelIds= from c in xdoc.Descendants("Model")
where c.Attribute("DESC").Value.StartsWith("VOLKS") &&
c.Attribute("Status").Value == "out"
select c.Attribute("MODELID").Value;
或使用正则表达式SQL LIKE
:
XDocument xdoc = XDocument.Load("data.xml"));
var modelIds= from c in xdoc.Descendants("Model")
where c.Attribute("DESC").Value.Like("VOLKS%") &&
c.Attribute("Status").Value == "out"
select c.Attribute("MODELID").Value;
为LIKE使用正则表达式:
public static class MyStringExtensions
{
public static bool Like(this string toSearch, string toFind)
{
return new Regex(@"\A" + new Regex(@"\.|\$|\^|\{|\[|\(|\||\)|\*|\+|\?|\\").Replace(toFind, ch = > @"\" + ch).Replace('_', '.').Replace(" % ", ".*") + @"\
z ", RegexOptions.Singleline).IsMatch(toSearch);
}
}
答案 1 :(得分:0)
您没有提及LINQ是否正常。这是一个使用LINQ,foreach和XPATH的方法。 (为了加强Mihai已经发布的报道)。
static void Main(string[] args)
{
XmlDocument xd = new XmlDocument();
xd.Load("Models.xml");
var result = from XmlNode row in xd.DocumentElement.SelectNodes("//Model[starts-with(@DESC, 'VOLKS') and @Status='out']") where row != null select row;
foreach (var x in result)
{
XmlAttributeCollection attributes = x.Attributes;
Console.Write("<Model ");
foreach (XmlAttribute attribute in x.Attributes)
{
Console.Write("{0}=\"{1}\" ", attribute.Name, attribute.Value);
}
Console.WriteLine(" />");
}
}
答案 2 :(得分:0)
使用lambdas的Linq to XML解决方案:
var query = XDocument.Load("data.xml").Root.Elements("Model")
.Where(m => m.Attribute("Status").Value == "out" && m.Attribute("DESC").Value.StartsWith("VOLKS"))
.Select(m => m.Attribute("MODELID").Value);
foreach (var v in query)
Console.WriteLine(v);
// output:
// BG12-01
// XJ11-61
// LK11-61