C# 如何以高效的方式解析此xml?
我是C#的初学者 更大案例的简单示例: 输入:C# 如何以高效的方式解析此xml?,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我是C#的初学者 更大案例的简单示例: 输入: <?xml version="1.0" encoding="utf-8"?> <products> <product> <id>1</id> <name>John</name> </product> <product> <id>2</id> <name>Tom</
<?xml version="1.0" encoding="utf-8"?>
<products>
<product>
<id>1</id>
<name>John</name>
</product>
<product>
<id>2</id>
<name>Tom</name>
</product>
<product>
<id>3</id>
<name>Sam</name>
</product>
</products>
</xml>
<id>2</id>
<name>Tom</name>
XDocument doc=XDocument.Parse(".............");
var els= doc.Descendants("product");
foreach(e in els){
node=e.Element("id");
if(2==node.Value){
return e;
}
}
请帮忙
谢谢当前您的xml文件格式不正确-请从文件中删除关闭标记以使其有效。以下是查询:
int id = 1;
XDocument xdoc = XDocument.Load(path_to_xml);
var product = xdoc.Descendants("product")
.Where(p => (int)p.Element("id") == id)
.SingleOrDefault();
如果未找到匹配项,此查询将返回整个
元素或null
此外,我相信产品名称足以供您选择(因为您已经有产品id):
返回
Tom
对于id=2
您可能正在查找XPath:
root.XPathSelectElements(@"//products/product/id[text()='2']")
编辑注释:直接获取名称://products/product/id[text()='2']/../name
请参阅完整示例
using System.Xml.Linq;
using System.Xml.XPath;
public class Program
{
public static void Main(string[] args)
{
var doc = XDocument.Parse(XML);
foreach(var n in doc.Root.XPathSelectElements(
@"//products/product/id[text()='2']"))
{
System.Console.WriteLine("Not that hard: '{0}'", n.Parent.Element("name").Value);
}
// Direct query for name:
foreach(var n in doc.Root.XPathSelectElements(
@"//products/product/id[text()='2']/../name"))
{
System.Console.WriteLine("Directly: '{0}'", n.Value);
}
}
private const string XML =
@"<?xml version=""1.0"" encoding=""utf-8""?>
<products>
<product>
<id>1</id>
<name>John</name>
</product>
<product>
<id>2</id>
<name>Tom</name>
</product>
<product>
<id>3</id>
<name>Sam</name>
</product>
</products>";
}
这将返回
产品
(如您的问题所示),而不是id
var product = doc.XPathSelectElement("//product[id and id[text() = '1']]");
谢谢,我还需要打印“name”@Yosef,你为什么不打印呢
Console.WriteLine(“不是那么难:'{0}',n.Parent.Element(“name”).Value)
。打印没那么难:“Tom”@Yosef我已经修改了示例,以显示直接查询名称的XPathinstead@Yosef刚刚验证-我没有错误。您修复了xml文件了吗?您会收到什么样的错误?
Not that hard: 'Tom'
Directly: 'Tom'
var product = doc.XPathSelectElement("//product[id and id[text() = '1']]");