查找名为“标签”的元素和名为“标题”

时间:2015-11-16 22:55:28

标签: c# xml

在下面的XML字符串中......我需要生成所有字幕的列表,以便快速浏览XML字符串中的各种数据元素。为了实现这一点,我想在所有'Label'元素中找到所有'Caption'属性的值。 有关如何实现这一目标的任何建议?

以下是我正在使用的c#代码示例...

XmlDocument xDoc = new XmlDocument();
string captionField = string.Empty;
xDoc.Load(xmlFilePath);

foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
{
    // first node is the url ... have to go to nexted loc node 
    foreach (XmlNode locNode in node)
    {
        // thereare a couple child nodes here so only take data from node named loc 
        if (locNode.Name == "Label")
        {
            foreach (XmlNode item in node.ChildNodes)
            {
                captionField = locNode.Attributes["Caption"].Value;
                if(!String.IsNullOrEmpty(captionField))
                    WriteToFile(logiReportName + " - " + captionField, fileName, reportName);
            }
        }
    }
}

xml数据:

 <?xml version="1.0" encoding="utf-8"?>
<Report ID="GenericMissedOpportunity" SavedBy="" SavedAt="10/29/2015 3:47:23 PM" EngineVersion="12.0.036-SP3" SecurityReportRightID="Accounting">
  <StyleSheet Theme="Clarity" />
  <ReportHeader>
    <Label Caption="Generic Missed Opportunity" Class="ThemeHeaderLarger" />
    <LineBreak />
    <Label Caption="This report shows transactions where a brand was used but a generic was available." />
    <Spaces Size="10" />
    <LineBreak />
    <LineBreak />
    <Division ID="divFilters">
      <InputDate ID="idBeginDateRange" SaveInCookie="True" ShowDateRange="True" Caption="Begin Date" CalendarLinkType="Image" EndDateRangeID="idEndDateRange" EndDateRangeCaption="End Date" InputSize="7px" DefaultValue="@Cookie.idBeginDateRange~" EndDateDefaultValue="@Cookie.idEndDateRange~" />
      <Spaces Size="10" />
      <InputCheckboxList OptionCaptionColumn="AltName" ID="parmLocation" OptionValueColumn="IRXLocationId" Caption="Choose a Store " CaptionClass="ThemeAlignLeft" DefaultValue="@Cookie.parmLocation~" CheckboxListDropdown="True" MultiSelect="True" SaveInCookie="True" Tooltip="@Request.parmLocation~" IdeDisplayStatus="Collapsed">
        <DataLayer Type="SQL" ID="dlLocation" ConnectionID="IntellectRX-DataWarehouse" Source="SELECT A.IRXLocationId, A.Name, A.AltName&#xD;&#xA;FROM Dimension.Location A&#xD;&#xA;WHERE A.AltName IS NOT NULL&#xD;&#xA;  AND (CAST(A.ClientID AS VARCHAR(64)) = @SingleQuote.Session.ClientId~)&#xD;&#xA;ORDER BY A.AltName" />
      </InputCheckboxList>
      <Spaces Size="10" />
      <Button Caption="Create Report" ID="btnSubmit" IdeDisplayStatus="Collapsed">
        <Action Type="RefreshElement" ID="arDivReportBody" ElementID="DivOuter" EnterKeyDefault="True">
          <LinkParams parmShowDataTable="True" />
          <WaitPage />
        </Action>
      </Button>
      <Spaces Size="10" />
    </Division>
    <LineBreak />
    <HR />
  </ReportHeader>
  <Body>
    <Division ID="DivOuter">
      <Division ID="divReportBody" Condition="&quot;@Request.parmShowDataTable~&quot; == &quot;True&quot;" HtmlDiv="True">
        <Label Caption="Export CSV">
          <Action Type="CSV" IdeDisplayStatus="Collapsed">
            <Target Type="CSV" ExportFilename="GenericMissedOpportunity.csv" Report="GenericMissedOpportunity" />
            <LinkParams parmShowDataTable="True" />
          </Action>
        </Label>
        <DataTable SortArrows="True" ID="DataTable1" AjaxPaging="True" DraggableColumns="True" Layout="Auto" Width="100" WidthScale="%" KeepScrollPosition="True" RememberSort="True" ResizableColumns="True">
          <DataLayer Type="SQL" ID="dlGenericMissedOpportunity" ConnectionID="IntellectRX-DataWarehouse" Source="select A.RxID, B.ItemId, B.ItemName, E.RXNumber, D.AltName, B.LabelTypeID, B.GCN, A.DawCodePostEditStatusTypeID, A.DateFilled, b.NDC, a.DawCodeID, C.PostEditStatusText,&#xD;&#xA; Generic = (select top 1 G.ItemName FROM [IntellectRX-DataWarehouse].Dimension.Item G WHERE B.GCN = G.GCN AND G.LabelTypeID = 1 and A.IRXLocationId = G.IRXLocationId )&#xD;&#xA;    FROM [IntellectRX-DataWarehouse].Fact.RxTransaction A with (nolock)&#xD;&#xA;   JOIN [IntellectRX-DataWarehouse].Dimension.Item B with (nolock) on A.DispensedItemID = B.ItemID AND a.IRXLocationId = B.IRXLocationId&#xD;&#xA; JOIN [IntellectRX-DataWarehouse].Dimension.Rx E with (nolock) on A.RxID = E.RxID AND A.IRXLocationId = E.IRXLocationId&#xD;&#xA;    JOIN [IntellectRX-DataWarehouse].Dimension.Location D with (nolock) on A.IRXLocationId = D.IRXLocationId&#xD;&#xA;  JOIN [IntellectRX-DataWarehouse].Dimension.PostEditStatusType C with (nolock) on A.DawCodePostEditStatusTypeID = C.PostEditStatusTypeID&#xD;&#xA;   &#xD;&#xA;  where B.LabelTypeID = 2 AND&#xD;&#xA;   A.DawCodePostEditStatusTypeID &gt; 0&#xD;&#xA;  AND (CAST(A.ClientID AS VARCHAR(64)) = @SingleQuote.Session.ClientId~)&#xD;&#xA;    AND (Cast(b.IRXLocationId As VARCHAR(64)) IN (@SingleQuote.Request.parmLocation~))&#xD;&#xA;    AND A.DateFilled between @StartDate and @EndDate&#xD;&#xA;  AND (select top 1 G.ItemName FROM [IntellectRX-DataWarehouse].Dimension.Item G WHERE B.GCN = G.GCN AND G.LabelTypeID = 1 and A.IRXLocationId = G.IRXLocationId) is not null&#xD;&#xA;   ORDER BY D.AltName, DateFilled DESC" IdeDisplayStatus="Collapsed">
            <SqlParameters>
              <SqlParameter ID="StartDate" Value="@Request.idBeginDateRange~" SqlParamType="dt-133" />
              <SqlParameter ID="EndDate" Value="@Request.idEndDateRange~" SqlParamType="dt-133" />
            </SqlParameters>
          </DataLayer>
          <DataTableColumn ID="colStore" Header="Store" IdeDisplayStatus="Collapsed">
            <Label ID="lblStore" Caption="@Data.AltName~" />
            <DataColumnSort DataColumn="AltName" DataType="Text" />
          </DataTableColumn>
          <DataTableColumn ID="colRXNumber" Header="RX Number" IdeDisplayStatus="Collapsed">
            <Label ID="lblRXnumber" Caption="@Data.RXNumber~" />
            <DataColumnSort DataColumn="RXNumber" DataType="Text" />
          </DataTableColumn>
          <DataTableColumn ID="colDateFilled" Header="DateFilled" IdeDisplayStatus="Collapsed">
            <Label ID="lblDateFilled" Caption="@Data.DateFilled~" Format="Short Date" />
            <DataColumnSort DataColumn="DateFilled" DataType="Date" />
          </DataTableColumn>
          <DataTableColumn ID="colNDC" Header="NDC" IdeDisplayStatus="Collapsed">
            <Label ID="lblNDC" Caption="@Data.NDC~" Format="00000-0000-00" />
            <DataColumnSort DataColumn="NDC" />
          </DataTableColumn>
          <DataTableColumn ID="colGCN" Header="GCN" IdeDisplayStatus="Collapsed">
            <Label ID="lblGCN" Caption="@Data.GCN~" />
            <DataColumnSort DataColumn="GCN" />
          </DataTableColumn>
          <DataTableColumn ID="colPostEditStatusText" Header="Post Edit Status" IdeDisplayStatus="Collapsed">
            <Label ID="lblPostEditStatusText" Caption="@Data.PostEditStatusText~" />
            <DataColumnSort DataColumn="PostEditStatusText" />
          </DataTableColumn>
          <DataTableColumn ID="colDawCodeID" Header="DAW" IdeDisplayStatus="Collapsed">
            <Label ID="lblDawCodeID" Caption="@Data.DawCodeID~" />
            <DataColumnSort DataColumn="DawCodeID" DataType="Number" />
          </DataTableColumn>
          <DataTableColumn ID="colItemName" Header="Brand" IdeDisplayStatus="Collapsed">
            <Label ID="lblItemName" Caption="@Data.ItemName~" />
            <DataColumnSort DataColumn="ItemName" />
          </DataTableColumn>
          <DataTableColumn ID="colGeneric" Header="Generic" IdeDisplayStatus="Collapsed">
            <Label ID="lblGeneric" Caption="@Data.Generic~" />
            <DataColumnSort DataColumn="Generic" />
          </DataTableColumn>
          <InteractivePaging PageRowCount="250" ShowPageNumber="Numbered" Location="Top" HideShowPrevNextCaptions="True" CaptionType="Text" HideWhenOnePage="True" />
        </DataTable>
      </Division>
    </Division>
  </Body>
  <ReportFooter />
  <ideTestParams idBeginDateRange="" idEndDateRange="" parmLocation="" parmShowDataTable="" />
</Report>

2 个答案:

答案 0 :(得分:1)

为简单起见,我建议您使用Linq to XML

使用Linq To XML,您可以在导入System.Linq.Xml namesapce之后编写类似此代码的简单内容:

 var xDoc = XDocument.Load(xmlFilePath);
 var captionValues = xDoc.Descendants("Label").Select(p => (string) p.Attribute("Caption")).ToList();

captionValues变量中,您将在Caption元素中的Label属性上定义所有值。使用此值集合,您可以执行所需的操作,例如将其写入文件。

答案 1 :(得分:1)

XPath会做你想做的事:

XmlNodeList MyList = xDoc.SelectNodes("/Report/ReportHeader/Label");

foreach (XmlNode Node in MyList)
{
    captionField = Node.Attributes["Caption"].Value;
}