retrieving distinct attributes from xml doc

  • Thread starter Thread starter rds80
  • Start date Start date
R

rds80

In the xml document below, I would like to retrieve the distinct
attributes for the element '<Bal>'. However, I haven't had any
success. Here is what I have so far:



<TRANS>

<TRAN TRAN_DESC_CD="ACRT" TRAN_DESC="Actual Rate">

<BAL BAL_FLD_NUM="3" BAL_FLD_DSCR="Actual Rate Amount">

<SUBDEAL SUB_Deal_ID="0011-01" />

</BAL>

<BAL BAL_FLD_NUM="3" BAL_FLD_DSCR="Actual Rate Amount">

<SUBDEAL SUB_Deal_ID="0013-01" />

</BAL>

<BAL BAL_FLD_NUM="2" BAL_FLD_DSCR="Actual Rate Amount">

<SUBDEAL SUB_Deal_ID="00112-01" />

</BAL>

<BAL BAL_FLD_NUM="6" BAL_FLD_DSCR="Actual Dispersion Amount">

<SUBDEAL SUB_Deal_ID="02342-01" />

</BAL>

</TRAN>

</TRANS>



IEnumerable<XAttribute> ICOA =

(from ddList in GxmlCOA.Descendants("BAL").Attributes()

select ddList).Distinct();



So the distinct bal fields should be:

1) Text = "Actual Rate Amount"

Val = 3

2) Text = "Actual Rate Amount"

Val = 2

3) Text = "Actual Dispersion Amount"

Val = 6



Unfortunately, the LINQ query isn't working.
 
Hi

You could create your own object, which overrides Equal and
GetHashCode. Something like:

using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

public class DistinctAttr {
public static void Main(string[] args)
{
XElement el = XElement.Load("DistinctAttr.xml");
var attrs =
el.Descendants("BAL").
Select(e =>
new MyAttr
{
Num = e.Attribute("BAL_FLD_NUM").Value,
Dscr = e.Attribute("BAL_FLD_DSCR").Value
}
).Distinct();
foreach(var at in attrs)
{
Console.WriteLine("num: {0}, dscr: {1}", at.Num, at.Dscr);
}
}

class MyAttr
{
private string _num, _dscr;
public override bool Equals(object obj)
{
if(obj == null || !(obj is MyAttr)) return false;
MyAttr at = (MyAttr) obj;
return this._num == at.Num && this._dscr == at.Dscr;
}

public override int GetHashCode()
{
return (int) (_num.GetHashCode() + _dscr.GetHashCode());
}

public string Num {get{return this._num;} set{this._num = value;}}
public string Dscr {get{return this._dscr;} set{this._dscr =
value;}}
}
}

Regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top