简体   繁体   中英

How to read multiple tags with same name under child node in a xml file using c#?

For below xml i want to read all row nodes value, as you can see there are multiple row tags under subcategory tag, so for particular subcategory(suppose for SubCategory ID="Standard") i want to fetch all row tags? How to do this using c#?

<DPS>
  <Category ID="Handsets">
    <Device ID="Samsung">
      <Contract ID="twoFour">
        <Tariff ID="Standard4G">
          <SubCategory ID="Standard">
            <Row>
              <Minutes>"Minutes":"999999"</Minutes>
              <Texts>"Texts":"99999"</Texts>
              <Data>"Data":"10000"</Data>
              <Content>"Content":"No"</Content>
              <Roaming>"Roaming":"Y + 2000"</Roaming>
              <Monthly>"Monthly":"38"</Monthly>
              <Upfront>"Upfront":0"</Upfront>
            </Row>
            <Row>
              <Minutes>Minutes:999</Minutes>
              <Texts>Texts:99994569</Texts>
              <Data>Data:100</Data>
              <Content>Content:No</Content>
              <Roaming>Roaming:Y + 2000</Roaming>
              <Monthly>Monthly:398</Monthly>
              <Upfront>Upfront:0</Upfront>
            </Row>
            <Row>
              <Minutes>Minutes:99</Minutes>
              <Texts>Texts:92569</Texts>
              <Data>Data:10</Data>
              <Content>Content:No</Content>
              <Roaming>Roaming:Y + 2000</Roaming>
              <Monthly>Monthly:38</Monthly>
              <Upfront>Upfront:0</Upfront>
            </Row>
          </SubCategory>
          <SubCategory ID="RedValue">
            <Row>
              <Minutes>"Minutes":"999999"</Minutes>
              <Texts>"Texts":"99999"</Texts>
              <Data>"Data":"10000"</Data>
              <Content>"Content":"No"</Content>
              <Roaming>"Roaming":"Y + 2000"</Roaming>
              <Monthly>"Monthly":"38"</Monthly>
              <Upfront>"Upfront":0"</Upfront>
            </Row>
            <Row>
              <Minutes>Minutes:999</Minutes>
              <Texts>Texts:99994569</Texts>
              <Data>Data:100</Data>
              <Content>Content:No</Content>
              <Roaming>Roaming:Y + 2000</Roaming>
              <Monthly>Monthly:398</Monthly>
              <Upfront>Upfront:0</Upfront>
            </Row>
            <Row>
              <Minutes>Minutes:99</Minutes>
              <Texts>Texts:92569</Texts>
              <Data>Data:10</Data>
              <Content>Content:No</Content>
              <Roaming>Roaming:Y + 2000</Roaming>
              <Monthly>Monthly:38</Monthly>
              <Upfront>Upfront:0</Upfront>
            </Row>
          </SubCategory>
        </Tariff>
      </Contract>
    </Device>
  </Category>
</DPS>

First, load the XML into an XDocument.

var xdoc = XDocument.Parse(xml); // Or XDocument.Load(pathToXmlFile), etc....

Then you can query all the SubCategory elements for the one with the ID of "Standard" and lastly ask for all of its child elements, the rows.

var rows = xdoc.Descendants("SubCategory")
  .Where(sc => sc.Attribute("ID").Value == "Standard")
  .Elements();

Edit : To get the actual values from the above XML, this is one way to do it.

I made an inline function to get a given element from the row by name and handle stripping out unwanted characters from it.

Func<XElement, string, string> getElementValue = (XElement row, string name)
    => row.Element(name).Value
        .Split(':').Last() // Take only the right side of the colons
        .Trim('"'); // Remove the double quotes, if any

Then, we can use it to get all the expected properties for each row:

var rowData = rows.Select(x => new {
    Minutes = getElementValue(x, "Minutes"),
    Texts = getElementValue(x, "Texts"),
    Data = getElementValue(x, "Data"),
    Content = getElementValue(x, "Content"),
    Roaming = getElementValue(x, "Roaming"),
    Monthly = getElementValue(x, "Monthly"),
    Upfront = getElementValue(x, "Upfront")
});

For real usage, you'll probably want to make a class with the properties like Minutes, Texts, etc. defined on it if you don't already and then put that class name after the new keyword where the rows are being selected.

Edit 2 : With the extra bits of text in each element acknowledged as "typing error", you can skip the inline function altogether and simplify the rowData select to this:

var rowData = rows.Select(x => new {
    Minutes = x.Element("Minutes").Value,
    Texts = x.Element("Texts").Value,
    Data = x.Element("Data").Value,
    Content = x.Element("Content").Value,
    Roaming = x.Element("Roaming").Value,
    Monthly = x.Element("Monthly").Value,
    Upfront = x.Element("Upfront").Value
});

This VB code could not be converted to C# using the converter I have access to. I knew the XML literal doesn't have a counterpart in C#, but isn't needed for anything but to have some test data.

Since the XML seems well structured I created a series of classes that mimics the data. They are just a starting point because I didn't know the ins and outs of the data.

Lets start at the end by looking at each row in Standard. Debugs were added to help visualize.

    Dim myDPS As New DPS(xe)
    myDPS.Category.Device.Tariff.SubCategory.GetOnePart("Standard")
    Debug.WriteLine(myDPS.Category.Device.Tariff.SubCategory.OnePart.ToString)
    For Each el As XElement In myDPS.Category.Device.Tariff.SubCategory.Row.OnePart.Elements
        Debug.WriteLine(el.ToString)
    Next

Here are the classes.

Public Class DPS : Inherits DPSBaseClass

    Public Category As DPSCategory

    Public Sub New(path As String)
        MyBase.New(XElement.Load(path))
    End Sub

    Public Sub New(element As XElement)
        MyBase.New(element)
        If Me.OnePart IsNot Nothing Then
            Me.Category = New DPSCategory(Me.OnePart)
        End If
    End Sub
End Class

Public Class DPSCategory : Inherits DPSBaseClass

    Public Device As DPSDevice

    Public Sub New(element As XElement)
        MyBase.New(element)
        If Me.OnePart IsNot Nothing Then
            Me.Device = New DPSDevice(Me.OnePart)
        End If
    End Sub
End Class

Public Class DPSDevice : Inherits DPSBaseClass

    Public Tariff As DPSTariff

    Public Sub New(element As XElement)
        MyBase.New(element)
        If Me.OnePart IsNot Nothing Then
            Me.Tariff = New DPSTariff(Me.OnePart)
        End If
    End Sub
End Class

Public Class DPSTariff : Inherits DPSBaseClass

    Public SubCategory As DPSSubCategory

    Public Sub New(element As XElement)
        MyBase.New(element)
        If Me.OnePart IsNot Nothing Then
            Me.SubCategory = New DPSSubCategory(Me.OnePart)
        End If
    End Sub
End Class

Public Class DPSSubCategory : Inherits DPSBaseClass

    Public Row As DPSSubCategoryRow

    Public Sub New(element As XElement)
        MyBase.New(element)
        If Me.OnePart IsNot Nothing Then
            Me.Row = New DPSSubCategoryRow(Me.OnePart)
        End If
    End Sub
End Class

Public Class DPSSubCategoryRow : Inherits DPSBaseClass

    Public Sub New(element As XElement)
        MyBase.New(element)
    End Sub
End Class

Public MustInherit Class DPSBaseClass

    Private TheData As XElement
    Private DataParts As New List(Of XElement)
    Public OnePart As XElement

    Public Sub New(path As String)
        Me.New(XElement.Load(path))
    End Sub

    Public Sub New(element As XElement)
        Me.TheData = element
        Me.GetDataParts()
    End Sub

    Public Sub GetDataParts()
        Me.DataParts = (From el In Me.TheData.Elements Select el).ToList
        Me.GetOnePart("")
    End Sub

    Public Sub GetOnePart(ID As String)
        If Me.DataParts.Count > 0 Then
            If ID <> "" Then
                Me.OnePart = (From el In Me.DataParts Where el.@ID = ID Select el Take 1).FirstOrDefault
            Else
                Me.OnePart = Me.DataParts.FirstOrDefault
            End If
        End If
    End Sub

End Class

Here is that pesky XML literal that was used to test

    Dim xe As XElement = <DPS>
                             <Category ID="Handsets">
                                 <Device ID="Samsung">
                                     <Contract ID="twoFour">
                                         <Tariff ID="Standard4G">
                                             <SubCategory ID="Standard">
                                                 <Row>
                                                     <Minutes>"Minutes":"999999"</Minutes>
                                                     <Texts>"Texts":"99999"</Texts>
                                                     <Data>"Data":"10000"</Data>
                                                     <Content>"Content":"No"</Content>
                                                     <Roaming>"Roaming":"Y + 2000"</Roaming>
                                                     <Monthly>"Monthly":"38"</Monthly>
                                                     <Upfront>"Upfront":0"</Upfront>
                                                 </Row>
                                                 <Row>
                                                     <Minutes>Minutes:999</Minutes>
                                                     <Texts>Texts:99994569</Texts>
                                                     <Data>Data:100</Data>
                                                     <Content>Content:No</Content>
                                                     <Roaming>Roaming:Y + 2000</Roaming>
                                                     <Monthly>Monthly:398</Monthly>
                                                     <Upfront>Upfront:0</Upfront>
                                                 </Row>
                                                 <Row>
                                                     <Minutes>Minutes:99</Minutes>
                                                     <Texts>Texts:92569</Texts>
                                                     <Data>Data:10</Data>
                                                     <Content>Content:No</Content>
                                                     <Roaming>Roaming:Y + 2000</Roaming>
                                                     <Monthly>Monthly:38</Monthly>
                                                     <Upfront>Upfront:0</Upfront>
                                                 </Row>
                                             </SubCategory>
                                             <SubCategory ID="RedValue">
                                                 <Row>
                                                     <Minutes>"Minutes":"999999"</Minutes>
                                                     <Texts>"Texts":"99999"</Texts>
                                                     <Data>"Data":"10000"</Data>
                                                     <Content>"Content":"No"</Content>
                                                     <Roaming>"Roaming":"Y + 2000"</Roaming>
                                                     <Monthly>"Monthly":"38"</Monthly>
                                                     <Upfront>"Upfront":0"</Upfront>
                                                 </Row>
                                                 <Row>
                                                     <Minutes>Minutes:999</Minutes>
                                                     <Texts>Texts:99994569</Texts>
                                                     <Data>Data:100</Data>
                                                     <Content>Content:No</Content>
                                                     <Roaming>Roaming:Y + 2000</Roaming>
                                                     <Monthly>Monthly:398</Monthly>
                                                     <Upfront>Upfront:0</Upfront>
                                                 </Row>
                                                 <Row>
                                                     <Minutes>Minutes:99</Minutes>
                                                     <Texts>Texts:92569</Texts>
                                                     <Data>Data:10</Data>
                                                     <Content>Content:No</Content>
                                                     <Roaming>Roaming:Y + 2000</Roaming>
                                                     <Monthly>Monthly:38</Monthly>
                                                     <Upfront>Upfront:0</Upfront>
                                                 </Row>
                                             </SubCategory>
                                         </Tariff>
                                     </Contract>
                                 </Device>
                             </Category>
                         </DPS>

Hope it sparks some ideas. Again, sorry for the VB. I did try to convert it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM