C# · 12月 30, 2021

c# – LINQ to XML – Elements()工作,但是Elements(XName)不起作用

以下是我的xml: <?xml version=”1.0″ encoding=”utf-8″?><Report xmlns:rd=”http://schemas.microsoft.com/sqlServer/reporting/reportdesigner” xmlns=”http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdeFinition”> <Body> <ReportItems> <Text@R_391_2419@ Name=”txtCurrentDate”> <CanGrow>true</CanGrow> <KeepTogether>true</KeepTogether> <Paragraphs> <Paragraph> <TextRuns> <TextRun> <Value>=Today()</Value> <Style> <FontWeight>Medium</FontWeight> <Format>d</Format> </Style> </TextRun> </TextRuns> <Style> <TextAlign>Left</TextAlign> </Style> </Paragraph> </Paragraphs> <Left>0.36958in</Left> <Height>0.22917in</Height> <Width>1in</Width> <Style> <Border> <Style>None</Style> </Border> <PaddingLeft>2pt</PaddingLeft> <PaddingRight>2pt</PaddingRight> <PaddingTop>2pt</PaddingTop> <PaddingBottom>2pt</PaddingBottom> </Style> </Text@R_391_2419@> <Text@R_391_2419@ Name=”txtName”> <CanGrow>true</CanGrow> <KeepTogether>true</KeepTogether> <Paragraphs> <Paragraph> <TextRuns> <TextRun> <Value>Mark Wilkinson</Value> <Style /> </TextRun> </TextRuns> <Style /> </Paragraph> </Paragraphs> <Top>0.22917in</Top> <Left>0.36958in</Left> <Height>0.20833in</Height> <Width>3.22917in</Width> <ZIndex>1</ZIndex> <Style> <Border> <Style>None</Style> </Border> <PaddingLeft>2pt</PaddingLeft> <PaddingRight>2pt</PaddingRight> <PaddingTop>2pt</PaddingTop> <PaddingBottom>2pt</PaddingBottom> </Style> </Text@R_391_2419@> </ReportItems> <Height>6.01667in</Height> <Style /> </Body> <Width>7.92333in</Width> </Report>

我想获取所有的Text@R_391_2419@名称和值.这是我尝试的,它不工作:

XDocument data = XDocument.Load(“..\\..\\testxml.rdl”); var elements = from c in data.Elements(“ReportItems”) select c; foreach (var element in elements) { Console.WriteLine(“Element : ” + element.Attribute(“Name”).Value); } Console.ReadKey();

但是当我将查询更改为这样的时候

var elements = from c in data.Elements().Elements().ElementAt(0).Elements().ElementAt(0).Elements() select c;

有用.

在这方面的任何帮助都非常感谢.

编辑:在答案的帮助下,我得到了所需的结果.非常感谢 :)

XDocument data = XDocument.Load(“..\\..\\testxml.rdl”); XNamespace ns = data.Root.Name.Namespace; var elements = from c in data.Descendants(ns + “Text@R_391_2419@”) select c; foreach (var element in elements) { Console.WriteLine(“Element : ” + element.Attribute(“Name”).Value); } Console.ReadKey();

TIA.

拉贾

解决方法 您需要考虑到命名空间: XNamespace df = data.Root.Name.Namespace;

然后使用df“foo”在根元素中定义的命名空间中选择具有本地名称foo的元素.

正如已经提到的,你可能想要选择后代,而不是子元素:

var elements = from c in data.Descendants(df + “Text@R_391_2419@”) select c;