read specific line this xml? - c#

Is there anyway to read the specific line in this xml?
http://i.stack.imgur.com/hDPIg.jpg
var guide = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameTitle = (string)query.Element("Title"),
Gamedescription = (string)query.Element("Description"),
GameGuide = (string)query.Element("Guide")
};
GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameGuide.StartsWith("See 'Payne In The Ass'")).Take(1);
this will show all guides in the xml.
This Work:
var guide = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameTitle = (string)query.Element("Title"),
Gamedescription = (string)query.Element("Description"),
GameGuide = (string)query.Element("Guide")
};
//GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameGuide.StartsWith("See 'Payne In The Ass'")).Take(1);
GuidesListBox.ItemsSource = guide.Where(ngc => ngc.GameTitle.StartsWith("Serious"));
So start with whatever is the first child in the XML.

Just continue your statement with a where clause: (change the condition based on your needs)
var guides = from query in dataFeed.Descendants("MaxPayne3")
select new NewGamesClass
{
GameGuide = (string)query.Element("Guide")
};
AchivementsListBox.ItemsSource = guides.Where( ngc => ngc.GameGuide.StartsWith("Chapter 4:"));

Related

XML reading - Deserialize vs XElement.Load

my question is fairly simple, which method should I use and why for parsing XML files?
Right now I have function for that:
return new EdiFile
{
SPPLR_MAILBOX = xmlDoc.Element("SPPLR_MAILBOX").Value,
MESSAGE_ID = xmlDoc.Element("MESSAGE_ID").Value,
ATTRIBUTE05 = xmlDoc.Element("ATTRIBUTE05").Value,
Levels0 = (from a in xmlDoc.Element("LEVELS0").Elements("LEVEL0")
select new Level0
{
PLT_NUM = a.Element("PLT_NUM").Value,
PLT_LABEL_ID = a.Element("PLT_LABEL_ID").Value,
BOX_QTY = a.Element("BOX_QTY").Value,
PLT_WEIGHT = a.Element("PLT_WEIGTH").Value,
PLT_DIMENSION = a.Element("PLT_DIMENSION").Value,
PLT_CHEM = a.Element("PLT_CHEM").Value,
PLT_NOT_STACK = a.Element("PLT_NOT_STACK").Value,
PLT_NOTE = a.Element("PLT_NOTE").Value,
ATTRIBUTE01 = a.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = a.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = a.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = a.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = a.Element("ATTRIBUTE05").Value,
Levels1 = (from b in a.Element("LEVELS1").Elements("LEVEL1")
select new Level1
{
BOX_NUM = b.Element("BOX_NUM").Value,
BOX_LABEL_ID = b.Element("BOX_LABEL_ID").Value,
Items = (from c in b.Element("ITEMS").Elements("ITEM")
select new Item
{
SPPLR_ITEM = c.Element("SPPLR_ITEM").Value,
CUST_ITEM = c.Element("CUST_ITEM").Value,
ATTRIBUTE01 = c.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = c.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = c.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = c.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = c.Element("ATTRIBUTE05").Value,
Lots = (from d in c.Element("LOTS").Elements("LOT")
select new Lot
{
LOT_NUM = d.Element("LOT_NUM").Value,
LOT_LABEL_ID = d.Element("LOT_LABEL_ID").Value,
LOT_NOTE = d.Element("LOT_NOTE").Value,
LOT_EXP_DATE = d.Element("LOT_EXP_DATE").Value,
QTY = d.Element("QTY").Value,
UOM = d.Element("UOM").Value,
ATTRIBUTE01 = d.Element("ATTRIBUTE01").Value,
ATTRIBUTE02 = d.Element("ATTRIBUTE02").Value,
ATTRIBUTE03 = d.Element("ATTRIBUTE03").Value,
ATTRIBUTE04 = d.Element("ATTRIBUTE04").Value,
ATTRIBUTE05 = d.Element("ATTRIBUTE05").Value
}).ToList()
}).ToList()
}).ToList()
}).ToList()
};
But should I use deserialize? I learnt about serialization yesterday.
I cant really find any source explaining my method, vs deserialization.
Can someone get me any insight please?
Your method is more performance and flexie, because you have control on processing xml file. Serialization is using reflection and it is less performance.

Check for missing elements while using LINQ to XML

I am trying get data from the xml. Below is the code which
gets data from the XDocument and return list<t>.
However, p.Element("Sponsor") can sometimes be null. How can I check for the null values
var atClauseList = doc.Descendants(CLAUSE_GROUP_TAG).Descendants(AT_CLAUSE_TAG).Select(p => new AtClause()
{
ClauseNumber = (string)p.Element("Number"),
Sponsors = p.Element("Sponsor").Elements(SPONSOR_TAG).Select(y => y.Value)
.ToList(),
Page = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Page").ElementValueNull(),
Line = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Line").ElementValueNull(),
LineText = p.Element("Sponsor").Element("aItem").Element("AmendText").Nodes().OfType<XText>().FirstOrDefault().XTextValueNull(),
ItalicText = p.Element("Sponsor").Element("aItem").Element("AmendText").Element("Italic").ElementValueNull(),
ParaList = p.Element("Sponsor").Element("aItem").Element("AmendText").Elements("Para").Select(L => new Para
{
ParaText = (string)L,
Number = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Number"),
Quote = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Quote"),
}
).ToList()
}).ToList();
move your code out of an object initializer, and add some logic to it:
var atClauseList = new List<AtClause>();
foreach(var item in doc.Descendants(CLAUSE_GROUP_TAG).Descendants(AT_CLAUSE_TAG))
{
var atClause = new AtClause();
atClause.ClauseNumber = (string)item.Element("Number");
var sponsor = item.Element("Sponsor");
if (sponsor != null)
{
atClause.Sponsors = sponsor.Elements(SPONSOR_TAG).Select(y => y.Value).ToList();
atClause.Page = sponsor.Element("aItem").Element("AmendText").Element("Page").ElementValueNull();
atClause.Line = sponsor.Element("aItem").Element("AmendText").Element("Line").ElementValueNull();
atClause.LineText = sponsor.Element("aItem").Element("AmendText").Nodes().OfType<XText>().FirstOrDefault().XTextValueNull();
atClause.ItalicText = sponsor.Element("aItem").Element("AmendText").Element("Italic").ElementValueNull();
atClause.ParaList = sponsor.Element("aItem").Element("AmendText").Elements("Para").Select(L => new Para
{
ParaText = (string)L,
Number = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Number"),
Quote = ((System.Xml.Linq.XElement)(L)).AttributeValueNull("Quote"),
}).ToList();
atClauseList.Add(atClause);
}
You can use sequences rather than leaving the IEnumerable immediately:
var value = (string)p.Elements("Sponsor")
.Elements("aItem")
.Elements("AmendText")
.Elements("Page")
.SingleOrDefault()

Error on using GroupBy in Linq

~ error says image seen below i don't know why is it? is there another way to pick up the data without the error? i'm using distinct or group by.
var query = (from i in SFC.TransacRRrecords where i.POPRCTNM == p
group i by new {
i.VendorID,
i.VENDNAME,
i.SUBTOTAL,
i.PymtrMID,
i.TRUCKNO,
i.REMARKS,
i.VPNum,
i.VPDate,
i.AmountInWords
} into grp
select new
{
Vcode = grp.Key.VendorID,
Vdesc = grp.Key.VENDNAME,
Vsubtotal = grp.Key.SUBTOTAL,
Vterms = grp.Key.PymtrMID,
Vtruckno = grp.Key.TRUCKNO,
Vremarks = grp.Key.REMARKS,
Vvpno = grp.Key.VPNum,
Vvpdate = grp.Key.VPDate,
Vamntword = grp.Key.AmountInWords
}).FirstOrDefault();
ListViewItem List = new ListViewItem(query.Vcode);
List.SubItems.Add(query.Vdesc);
List.SubItems.Add(string.Format("{0:n2}", query.Vsubtotal));
List.SubItems.Add(query.Vterms);
List.SubItems.Add(query.Vtruckno);
List.SubItems.Add(query.Vremarks);
List.SubItems.Add(query.Vvpno);
List.SubItems.Add(query.Vvpdate);
List.SubItems.Add(query.Vamntword);
deletedRRHeaderList.Items.AddRange(new ListViewItem[] { List });

LINQ to XML Get (children?) of element?

How would I go about getting the ID information using Linq. I'm trying to add them to an array of int.
<FactionAttributes>
<name>Player</name>
<id>0</id>
<relationModifier>1</relationModifier>
<relations>
<id0>100</id0>
<id1>50</id1>
<id2>50</id2>
<id3>50</id3>
<id4>50</id4>
<id5>50</id5>
</relations>
</FactionAttributes>
That is my XML.
Here is the code I'm using so far.
void InitFactions()
{
int count = 0;
string filepath = Application.dataPath + "/Resources/factiondata.xml";
XDocument factionXML = XDocument.Load(filepath);
var factionNames = from factionName in factionXML.Root.Elements("FactionAttributes")
select new {
factionName_XML = (string)factionName.Element("name"),
factionID_XML = (int)factionName.Element("id"),
factionRelations_XML = factionName.Element("relations")// Need to turn this into array.
};
foreach ( var factionName in factionNames)
++count;
foreach ( var factionName in factionNames)
{
Factions f = new Factions();
f.otherFactionsName = new string[count];
f.otherFactionsRelation = new int[count];
int others = 0;
f.FactionName = factionName.factionName_XML;
Debug.Log(factionName.factionRelations_XML);
// Adds Rivals, not self to other list.
foreach (var factionName2 in factionNames)
{
if (factionName.factionID_XML == factionName2.factionID_XML)
continue;
f.otherFactionsName[(int)factionName2.factionID_XML] = factionName2.factionName_XML;
// THIS IS WHERE IM ADDING THE RELATIONS IN //
f.otherFactionsRelation[(int)factionName2.factionID_XML] = factionName.factionRelations_XML[(int)factionName2.factionID_XML];
Debug.Log(f.FactionName + " adds: " + factionName2.factionName_XML);
++others;
}
}
}
I have made multiple attempts using nodes and what not. I can't seem to figure out the correct syntax.
XDocument doc = XDocument.Load(Path);
//To get <id>
var MyIds = doc.Element("FactionAttributes").Element("id").Value;
//To get <id0>, <id1>, etc.
var result = doc.Element("FactionAttributes")
.Element("relations")
.Elements()
.Where(E => E.Name.ToString().Contains("id"))
.Select(E => new { IdName = E.Name, Value = E.Value});
If you want array of ints replace the select with this
.Select(E => Convert.ToInt32(E.Value)).ToArray();
If you are just after the relations Ids use this simple query
var doc = XDocument.Load("c:\\tmp\\test.xml");
var ids = doc.Descendants("relations").Elements().Select(x => x.Value);
If you want the Id and the relations ids in one array use this
var id = doc.Descendants("id").Select(x=>x.Value).Concat(doc.Descendants("relations").Elements().Select(x => x.Value));

Is there a way to combine 2 LINQ2XML queries?

var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements()
}).SingleOrDefault();
var fields = from item in instructions.fields
select new
{
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
};
I think something like this should work. I added the Select method to return the anonymous class.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = item.Element("fields").Elements().Select(item => new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
}
).SingleOrDefault();
If you don't want to use the Select Extension method, you can use LINQ syntax. Here is an example of this.
var instructions = (from item in config.Elements("import")
select new
{
name = item.Attribute("name").Value,
watchFolder = item.Attribute("watchFolder").Value,
root = item.Element("documentRoot").Value,
DocumentNameDynamic = item.Element("documentName").Attribute("xpath").Value,
DocumentNameStatic = item.Element("documentName").Attribute("static").Value,
TemplateName = item.Element("template").Attribute("template").Value,
Path = item.Element("path").Attribute("path").Value,
fields = from e in item.Element("fields").Elements()
select new {
xpath = item.Attribute("xpath").Value,
FieldName = item.Attribute("FieldName").Value,
isMultiValue = bool.Parse(item.Attribute("multiValue").Value)
} // End of inner select statement
} // End of outer select statement
).SingleOrDefault();

Categories

Resources