且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用C#在Xml文件中读取子节点

更新时间:2022-10-22 15:08:26

您需要先修复XML文档 - 它目前有多个根节点,这是不允许的。



要解析它,请尝试Linq to XML:

https://msdn.microsoft.com/en-us/library/bb387098.aspx [ ^ ]

XLINQ简介第3部分,共3部分 [ ^ ]

 XDocument document = XDocument.Load(  path \to\your\file.xml); 

IEnumerable< xelement> query =
来自 XElement el doc.Descendants( 报告
name =(( string )el.Element( ReportName)? ? string .Empty).Trim()
其中 string .Equals(name,theReportNameToFind,StringComparison.Ordinal)
select el;

XElement reportNode = query.First();
// 如果没有匹配的报告,则抛出异常。
// 或者,使用FirstOrDefault并检查空返回值。

string procedureName =( string )reportNode.Element( StoredProcName);
< / xelement > 跨度>


Hi,


I have an XMLFile in my solution called XMLFile.xml. It contains following data.

<Report>
    <ReportName>
      Daily
    </ReportName>
    <StoredProcName>sp_GetDatafromTB</StoredProcName>
  </Report>
  <Report>
    <ReportName>
      Weekly
    </ReportName>
    <StoredProcName>sp_GetDatafromTable</StoredProcName>
  </Report>
  <Report>
    <ReportName>
      Monthly
    </ReportName>
    <StoredProcName>sp_GetDatafromTB</StoredProcName>
  </Report>
  <Report>
    <ReportName>
      Yearly
    </ReportName>
    <StoredProcName>sp_GetDatafromTable</StoredProcName>
  </Report>





Now on button click event i need to parse the xml file and and get the name of the StoredProcName when the name of the ReportName is equal to the name of the item selected in the dropdownlist (in UI) and bind it to a gridview. I am able to parse XML file but i how do i get name of the child node which can be used to run stored procedure. Please help me.

You'll need to start by fixing the XML document - it currently has multiple root nodes, which is not allowed.

To parse it, try Linq to XML:
https://msdn.microsoft.com/en-us/library/bb387098.aspx[^]
XLINQ Introduction Part 3 Of 3[^]
XDocument document = XDocument.Load("path\to\your\file.xml");

IEnumerable<xelement> query = 
    from XElement el in doc.Descendants("Report")
    let name = ((string)el.Element("ReportName") ?? string.Empty).Trim()
    where string.Equals(name, theReportNameToFind, StringComparison.Ordinal)
    select el;

XElement reportNode = query.First();
// This throws an exception if there are no matching reports.
// Alternatively, use "FirstOrDefault" and check for a null return value.

string procedureName = (string)reportNode.Element("StoredProcName");
</xelement>