Add new XEelement and Update XML.Descendent - c#

I have this code that works well, but I can't seem to figure out how to actually save the update XML.descendents list = JobNames to the XML document.
public void ProcessJobNames(String JobName = null, Boolean rRemove = false)
{
System.Xml.Linq.XDocument xml = System.Xml.Linq.XDocument.Load(_JobPath + #"\" + _ConfigFile);
var JobNames = xml.Descendants("setting").Where(xe => xe.Attribute("key").Value.Contains("JobType")).ToList();
System.Xml.Linq.XElement copyXE = null;
int JobCount = 0;
foreach (System.Xml.Linq.XElement strJobName in JobNames)
{
//strJobNames.Add(strJobName.LastAttribute.Value.ToString());
JobCount = JobCount + 1;
strJobName.FirstAttribute.Value = "JobType" + (JobCount).ToString();
copyXE = strJobName; // Make a copy of the Job
// Check if the JobName is in the Job Processor to be Removed
if ((JobName != null) && (rRemove == true) && (strJobName.LastAttribute.Value.ToString().Contains(JobName)))
{
// Remove the Job from the Configuration File
strJobName.Remove();
JobCount = JobCount - 1;
}
// Check if the JobName is in the Job Processor to be Added
if ((JobName != null) && (rRemove == false) && (strJobName.LastAttribute.Value.ToString().Contains(JobName)))
{
// Add the Job from the Configuration File
strJobName.Remove();
JobCount = JobCount - 1;
}
}
// Add the new Job
if ((JobName != null) && (rRemove == false)) {
File.Copy(_RulesFolder + cmboRules.Text, _JobPath + cmboRules.Text);
System.Xml.Linq.XElement newJob = new System.Xml.Linq.XElement(copyXE);
newJob.FirstAttribute.Value = "JobType" + (JobCount + 1).ToString();
newJob.LastAttribute.Value = _JobPrefix + cmboRules.Text;
copyXE.Parent.Add(newJob)
}
// Save the XML Configuration File
xml.Save(_JobPath + _ConfigFile);
}
I think I'm missing something after "JobNames.Add(newJob)" to update the descendants in the XML document.

To add a node in runtime, You could use XElement.Parent.Add()method to add child. For example,
foreach(var job in jobList)
{
if(job.Attribute("name").Value == "job1") //Any condition on which new node is to be added
{
var copy = job;
copy.Attribute("name").Value = "job3";
job.Parent.Add(copy);
}
}
Sample
Input
<root>
<jobs>
<job name="job1"></job>
<job name="job2"></job>
</jobs>
</root>
Output
<root>
<jobs>
<job name="job3"></job>
<job name="job2"></job>
<job name="job3"></job>
</jobs>
</root>

Related

How to get separate values from Xlement

This is a portion of XML I'm trying to parse
<BRTHDATES>
<BRTHDATE value="5/1/1963" code="B"/>
</BRTHDATES>
var birthdates = xmlDoc.XPathSelectElements("/INDV/PERSON/BRTHDATES").Elements().Where(e => e.Name == "BRTHDATE");
xe = birthdates.Elements().Where(e => e.Name == "BRTHDATE");
bbs = from b in birthdates
select new
{
Birthdays = b.FirstAttribute.Value,
Code = b?.Value
};
var status = birthdates.Elements().Where(e => e.Name.LocalName == "BRTHDATE").Single().Value;
When I try to get "Value" from the Element I get an empty string. I can't get anything for the "code" attribute.
It sure seems like this should be a lot easier...
You can try below code. I've already tested through a test project and got the require value.
string personBirthday = string.Empty;
string soapResult = #"<?xml version=""1.0"" encoding=""utf - 8"" ?><INDV> <PERSON> <BRTHDATES><BRTHDATE value = ""5/1/1963"" code = ""B"" /> </BRTHDATES></PERSON></INDV> ";
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(soapResult));
XmlNodeList person = doc.GetElementsByTagName("BRTHDATES");
if (person[0].ChildNodes.Count > 0)
{
foreach (XmlNode item in person[0].ChildNodes)
{
if (item.Name.Trim().Equals("BRTHDATE"))
{
personBirthday = !string.IsNullOrEmpty(item.Attributes[0].Value) ? item.Attributes[0].Value.Trim() : string.Empty;
}
}
}
Here is the solution
You can select specific Element from a Xml. Just try below sample code
XmlNodeList generalTabNodeList = xmlDocument.SelectNodes("/INDV/PERSON/BRTHDATES");
foreach (XmlNode node in generalTabNodeList)
{
if (node.ChildNodes.Count > 0)
{
string birthdate = !string.IsNullOrEmpty(node.ChildNodes[0].ToString()) ? node.ChildNodes[2].InnerText.ToString() : string.Empty;
}
}
I can't quite follow what you are trying to do, but, this should get you going:
For an XML file that looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<INDV>
<PERSON>
<BRTHDATES>
<BRTHDATE value="5/1/1963" code="B"/>
</BRTHDATES>
</PERSON>
</INDV>
(Note, this is an entire XML document - one that matches your code, not just the snippet you provided (that doesn't match your code))
This code will pick out the value and code attributes:
using (var xmlStream = new FileStream("Test.xml", FileMode.Open))
{
XDocument xmlDocument = XDocument.Load(xmlStream);
var birthDateElements = xmlDocument.XPathSelectElements("/INDV/PERSON/BRTHDATES/BRTHDATE");
var birthDateElement = birthDateElements.FirstOrDefault();
if (birthDateElement != null)
{
var attributes = birthDateElement.Attributes();
var valueAttribute = attributes.Where(a => a.Name == "value");
var codeAttribute = attributes.Where(a => a.Name == "code");
}
}
You can play around with this code to figure out what you want to do. Whatever you do, don't pick out attributes by position, pick them out by name.

Convert a XML to CSV using C#

How to convert a XML file to a CSV file in C#, showing only these Tags: <original-impot-no>, <price>, <Small-price>, <Big-price>?
sample XML code: it represents one line among several lines, and every line may contains several <product-lineitem>Tags
<?xml version="1.0" encoding="UTF-8"?>
<impots xmlns="http://www.google.com/xml/impot//20016-02-31">
<impot impot-no="W0110891258">
<impot-date>2017-12-10T22:33:35.000Z</impot-date>
<prop-by>Yallo</prop-by>
<original-impot-no>891258</original-impot-no>
<currency>EUR</currency>
<server-locale>Esp</server-locale>
<lax>gross</lax>
<current-impot-no>123358</current-impot-no>
<product-lineitems>
<product-lineitem>
<price>450</price>
<red>6.50</red>
<Small-price>39</Small-price>
<Big-price>3229</Big-price>
<lineitem-text>Grand create</lineitem-text>
<basis>234.00</basis>
</product-lineitem>
</product-lineitems>
<product-lineitem>
<price>432</price>
<red>12</red>
<Small-price>44</Small-price>
<Big-price>34</Big-price>
<lineitem-text>Small create</lineitem-text>
<basis>44.00</basis>
</product-lineitem>
</product-lineitems>
</impot>
</impots>
I should get someting like this in y CSV file:
891258;450;39;229
891258;432;44;34
the C# code:
the problem that Im facing with this code is that I can not retrieve the descandent of the TAG <impot>
XmlTextReader xtr = new XmlTextReader(#"C:\Temp_Convert\Impot.xml");
StringBuilder dataToBeWritten = new StringBuilder();
while (xtr.Read())
{
if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "original-impot-no")
{
string s1 = xtr.ReadElementString();
dataToBeWritten.Append(s1);
dataToBeWritten.Append(";");
}
else if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "price")
{
string s2 = xtr.ReadElementString();
dataToBeWritten.Append(s2);
dataToBeWritten.Append(";");
}
else if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "Small-price")
{
string s2 = xtr.ReadElementString();
dataToBeWritten.Append(s2);
dataToBeWritten.Append(";");
dataToBeWritten.Append(0);
dataToBeWritten.Append(Environment.NewLine);
}
else if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "Big-price")
{
string s2 = xtr.ReadElementString();
dataToBeWritten.Append(s2);
dataToBeWritten.Append(";");
dataToBeWritten.Append(0);
dataToBeWritten.Append(Environment.NewLine);
}
}
File.WriteAllText(#"C:\Temp_Convert\Impot.csv", dataToBeWritten.ToString());
}
Can somebody please propose a solution, thank you so much in advance.
You have an invalid XML. I guess here is the correct format.
<?xml version="1.0" encoding="UTF-8"?>
<impots xmlns="http://www.google.com/xml/impot//20016-02-31">
<impot impot-no="W0110891258">
<impot-date>2017-12-10T22:33:35.000Z</impot-date>
<prop-by>Yallo</prop-by>
<original-impot-no>891258</original-impot-no>
<currency>EUR</currency>
<server-locale>Esp</server-locale>
<lax>gross</lax>
<current-impot-no>123358</current-impot-no>
<product-lineitems>
<product-lineitem>
<price>450</price>
<red>6.50</red>
<Small-price>39.00</Small-price>
<Big-price>3229.00</Big-price>
<lineitem-text>Grand create</lineitem-text>
<basis>234.00</basis>
</product-lineitem>
</product-lineitems>
<product-lineitems>
<product-lineitem>
<price>432</price>
<red>12</red>
<Small-price>44.00</Small-price>
<Big-price>34.00</Big-price>
<lineitem-text>Small create</lineitem-text>
<basis>44.00</basis>
</product-lineitem>
</product-lineitems>
</impot>
</impots>
You couldn't retrieve the descendant because you are not including the namespace http://www.google.com/xml/impot//20016-02-31.
Here is how the code should be.
XNamespace ns = "http://www.google.com/xml/impot//20016-02-31";
var results = xDocument.Descendants(ns + "impot");
Then, you need to modify your query to retrieve elements that you need.
Here is the sample. I assume that product-lineitems only has one child product-lineitem.
var results = xDocument.Descendants(ns + "impot").Select(x => new {
ImpotNo = x.Attribute("impot-no")?.Value,
ProductLineItems = x.Descendants(ns + "product-lineitems").Select(y => new
{
Item = y.Descendants(ns + "product-lineitem").Select(z => new
{
Price = z.Element(ns + "price")?.Value,
SmallPrice = z.Element(ns + "Small-price")?.Value,
BigPrice = z.Element(ns + "Big-price")?.Value,
}).FirstOrDefault()
})
});
foreach (var result in results)
{
foreach (var productLine in result.ProductLineItems)
{
dataToBeWritten.Append(result.ImpotNo);
dataToBeWritten.Append(";");
dataToBeWritten.Append(productLine.Item.Price);
dataToBeWritten.Append(";");
dataToBeWritten.Append(productLine.Item.SmallPrice);
dataToBeWritten.Append(";");
dataToBeWritten.Append(productLine.Item.BigPrice);
dataToBeWritten.Append(";");
dataToBeWritten.Append(0);
dataToBeWritten.Append(Environment.NewLine);
}
}
Well, first I tried to reformat your XML to be a bit more readable but the tag structure still seems wrong...
<impots
xmlns="http://www.google.com/xml/impot//20016-02-31">
<impot impot-no="W0110891258">
<impot-date>2017-12-10T22:33:35.000Z</impot-date>
<prop-by>Yallo</prop-by>
<original-impot-no>891258</original-impot-no>
<currency>EUR</currency>
<server-locale>Esp</server-locale>
<lax>gross</lax>
<current-impot-no>123358</current-impot-no>
<product-lineitems>
<product-lineitem>
<price>450</price>
<red>6.50</red>
<Small-price>39.00</Small-price>
<Big-price>3229.00</Big-price>
<lineitem-text>Grand create</lineitem-text>
<basis>234.00</basis>
-
</product-lineitems>
-
</product-lineitem>
<product-lineitems>
<product-lineitem>
<price>432</price>
<red>12</red>
<Small-price>44.00</Small-price>
<Big-price>34.00</Big-price>
<lineitem-text>Small create</lineitem-text>
<basis>44.00</basis>
</product-lineitems>
</product-lineitem>
Nonetheless, I'm guessing this line is incorrect since "impot-no" is an attribute...
impot-no = (string)x.Element("impot impot-no")
Perhaps you meant that line to be...
impot-no = (string)x.Attribute("impot-no").Value
Going by memory -- hopefully that is the correct way to retrieve an attribute.
Review the following code. Note the use of SelectMany to get the impot items to construct the desired object models.
XNamespace ns = "http://www.google.com/xml/impot//20016-02-31";
var results = xDocument.Descendants(ns + "impot")
.SelectMany(impot => impot.Descendants(impot.Name.Namespace + "product-lineitem")
.Select(item => new {
ImpotNo = (string)impot.Element(impot.Name.Namespace + "original-impot-no"),
Price = (string)item.Element(item.Name.Namespace + "price"),
SmallPrice = (string)item.Element(item.Name.Namespace + "Small-price"),
BigPrice = (string)item.Element(item.Name.Namespace + "Big-price"),
})
).ToList();
for (int i = 0; i < results.Count; i++) {
dataToBeWritten.Append(results[i].ImpotNo);
dataToBeWritten.Append(";");
dataToBeWritten.Append(results[i].Price);
dataToBeWritten.Append(";");
dataToBeWritten.Append(results[i].SmallPrice);
dataToBeWritten.Append(";");
dataToBeWritten.Append(results[i].BigPrice);
dataToBeWritten.Append(";");
dataToBeWritten.Append(0);
dataToBeWritten.Append(Environment.NewLine);
}
Also note the syntax used for the properties.

Locate nodes in XML file

I have fixed my issue with reading the XML files. What I am needing now is to trim the datetime down to just MM dd yyyy hh:mm:ss and not bring the rest of it over when I insert into my Informix database.
This is the XML info:
<RecordFilingRequestMessage xmlns:nc="http://niem.gov/niem/niem-core/2.0">
<nc:DocumentIdentification>
<nc:IdentificationID>3212842</nc:IdentificationID>
</nc:DocumentIdentification>
<nc:DocumentPostDate>
<nc:DateTime>2013-06-25T11:32:08.5343733-04:00</nc:DateTime>
</nc:DocumentPostDate>
<nc:DocumentSubmitter>
<ecf:EntityPerson s:id="REVIEWER">
<nc:PersonName />
<nc:PersonOtherIdentification>
<nc:IdentificationID>41130</nc:IdentificationID>
<nc:IdentificationCategoryText>FLEPORTAL</nc:IdentificationCategoryText>
</nc:PersonOtherIdentification>
<nc:PersonOtherIdentification>
<nc:IdentificationID>kacolburn</nc:IdentificationID>
<nc:IdentificationCategoryText>FLEPORTAL_LOGONNAME</nc:IdentificationCategoryText>
</nc:PersonOtherIdentification>
...and here is my C# code:
string DocID = null;
int elementCount = 0;
string reqID = null;
string reqDateTime = null;
string empName = null;
string[] fileEntries = Directory.GetFiles(#"C:\XML\3212842.xml");
foreach (string fileName in fileEntries)
{
XmlReader xr = XmlReader.Create(fileName); //reads XML from folder
while (xr.Read())
{
if (xr.NodeType == XmlNodeType.Element && xr.Name == "nc:DateTime")
{
reqDateTime = xr.ReadElementContentAsString();
}
if (xr.NodeType == XmlNodeType.Element && xr.Name == "nc:IdentificationID")
{
elementCount++;
DocID = xr.ReadElementContentAsString();
if (elementCount == 1)
{
reqID = DocID;
}
if (elementCount == 3)
{
empName = DocID;
listBox1.Items.Add(reqID + " / " + reqDateTime + " / " + empName);
elementCount = 0;
break;
}
My first thought is, that the last '/' doesn't belong to the 'SelectNodes' call.
Alternatively, this code will solve your problem:
foreach(XmlNode node in xmlDoc.GetElementsByTagName("RecordFilingRequest")[0].GetElementsByTagName("nc:DocumentIdentification"))
{
int ID = Convert.ToInt32(node.FirstChild().InnerText);
}
Edit: This does assume, that 'RecordFilingRequest' always exists. Add a try .. catch statement, if that isn't the case.
Looks like the issue is that the XML uses namespaces, and your XPath does not. You didn't post your full XML, but you probably have something like xmlns:nc="http://some.url/ in there. Make sure to include a the namespace in a namespace manager, then add namespace prefixes to your query:
var nameTable = new NameTable();
var nsMgr = new XmlNamespaceManager(nameTable);
nsmgr.AddNamespace("nc", "http://some.url/");
var dataNodes = xmlDoc.SelectNodes("nc:RecordFilingRequest/nc:DocumentIdentification", nsMgr);
foreach (var node in dataNodes)
{
var ID = Convert.ToInt32(node.SelectSingleNode("nc:IdentificationID", nsMgr).InnerText);
// insert into database, e.g. using SqlCommand or whatever
}

LINQ to XML query depending on the tag names of the descendants

I have the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<sos:GetObservation xmlns="http://www.opengis.net/sos/2.0" service="SOS" version="2.0.0"
xmlns:sos="http://www.opengis.net/sos/2.0" xmlns:fes="http://www.opengis.net/fes/2.0"
xmlns:gml="http://www.opengis.net/gml/3.2" xmlns:swe="http://www.opengis.net/swe/2.0"
xmlns:swes="http://www.opengis.net/swes/2.0" xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opengis.net/sos/2.0
http://schemas.opengis.net/sos/2.0/sos.xsd">
<!--identifier of an offering-->
<offering>HG.Logger#DJK001</offering>
<!--identifier of an observed property-->
<observedProperty>HG</observedProperty>
<!--optional temporal filter restricting the results which shall be returned-->
<temporalFilter>
<fes:After>
<fes:ValueReference>phenomenonTime</fes:ValueReference>
<gml:TimeInstant gml:id="startPosition">
<gml:timePosition>2010-07-31T01:05:00</gml:timePosition>
</gml:TimeInstant>
</fes:After>
</temporalFilter>
<featureOfInterest>DJK001</featureOfInterest>
</sos:GetObservation>
Where the <temporalFilter> node can be replaced by either:
<temporalFilter>
<fes:Before>
<fes:ValueReference>phenomenonTime</fes:ValueReference>
<gml:TimeInstant gml:id="endPosition">
<gml:timePosition>2010-07-31T01:05:00</gml:timePosition>
</gml:TimeInstant>
</fes:Before>
</temporalFilter>
Or:
<temporalFilter>
<fes:During>
<fes:ValueReference>phenomenonTime</fes:ValueReference>
<gml:TimePeriod gml:id="duringPosition">
<gml:beginPosition>2010-07-31T01:05:00</gml:beginPosition>
<gml:endPosition>2010-07-31T01:06:00</gml:endPosition>
</gml:TimePeriod>
</fes:During>
</temporalFilter>
The following LINQ to XML code WORKS, but I need the code to be able to be able to handle any of the three temporalFilter possibilities I listed above. Does anybody have any suggestions?
private void GetTemporalFilterFromXml(GetObservation getObservation)
{
//var root = XElement.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var root = XElement.Parse(getObservation.ToXml(false, Formatting.None, EOLType.CRLF, RequestHandler.GetSos20Context()));
GetTemporalFilterDescendant(root); //Test line of code!
var query = (from level in root.Descendants(sos + "temporalFilter")
select new
{
valueReference = (string)level.Descendants(fes + "ValueReference").FirstOrDefault(),
timeInstant = (string)level.Descendants(gml + "TimeInstant").First().Attribute(gml + "id"),
timePosition = (string)level.Descendants(gml + "TimeInstant").Descendants(gml + "timePosition").First()
}).ToList();
if (query.Any() == false) return;
if (!String.IsNullOrEmpty(query[0].valueReference)) ValueReference = query[0].valueReference;
if (!String.IsNullOrEmpty(query[0].timePosition)) TimePosition = query[0].timePosition;
if (!String.IsNullOrEmpty(query[0].timeInstant)) TimeInstant = query[0].timeInstant;
}
EDIT: This is the code that I'm using in order to capture all the data that I need
{
//var root = XElement.Load(#"C:\Working Directory\OGCSOS.Service\OGCSOS.Service\Resources\GetObservation_TemporalFilter.xml");
var root = XElement.Parse(getObservation.ToXml(false, Formatting.None, EOLType.CRLF, RequestHandler.GetSos20Context()));
var query = (from x in root.Descendants(sos + "temporalFilter").Elements()
let timeInstant = x.Element(gml + "TimeInstant")
let timePeriod = x.Element(gml + "TimePeriod")
select new
{
valueReference = (string)x.Element(fes + "ValueReference"),
timeInstant = (timeInstant == null) ? null : timeInstant.Attribute(gml + "id").Value,
timePosition = (timeInstant == null) ? null : timeInstant.Element(gml + "timePosition").Value,
timePeriod = (timePeriod == null) ? null : timePeriod.Attribute(gml + "id").Value,
beginPosition = (timePeriod == null) ? null : timePeriod.Element(gml + "beginPosition").Value,
endPosition = (timePeriod == null) ? null : timePeriod.Element(gml + "endPosition").Value,
}).ToList();
if (query.Count == 0) return;
ValueReference = query[0].valueReference;
TimeInstant = query[0].timeInstant;
TimePosition = query[0].timePosition;
TimePeriod = query[0].timePeriod;
BeginTime = query[0].beginPosition;
EndTime = query[0].endPosition;
}
This will do the job. Elements() will return all three types of nodes - Before, After, and During. Introducing new range variable timeInstant allows to check if this node exists in element and handle During nodes:
var query = from x in root.Descendants(sos + "temporalFilter").Elements()
let timeInstant = x.Element(gml + "TimeInstant")
select new
{
valueReference = (string)x.Element(fes + "ValueReference"),
timeInstant = (timeInstant == null) ? null : (string)timeInstant.Attribute(gml + "id"),
timePosition = (timeInstant == null) ? null : (string)timeInstant.Element(gml + "timePosition")
};
BTW you can cast timePosition to (DateTime?) and Linq will give you nice DateTime object.

Count child nodes of node matching listbox item

Im having a problem here with selected index change. My xml file contains module number, module name, assesments, credits etc. What im trying to achieve here is - some course details are loaded into listbox from xml (module name and code) but when user selects a module, label should display how many assessments that module has.
Here is my XML file sample
<module>
<moduleCode>ECWM618</moduleCode>
<moduleTitle>Semantic and Social Web</moduleTitle>
<credits>15</credits>
<semester>2</semester>
<assessmentDetails>
<assessment>
<assessmentName>Coursework1</assessmentName>
<assessmentType>Coursework</assessmentType>
<assessmentWeighting>25</assessmentWeighting>
</assessment>
<assessment>
<assessmentName>Coursework2</assessmentName>
<assessmentType>Coursework</assessmentType>
<assessmentWeighting>25</assessmentWeighting>
</assessment>
<assessment>
<assessmentName>Exam</assessmentName>
<assessmentType>Exam</assessmentType>
<assessmentWeighting>50</assessmentWeighting>
</assessment>
</assessmentDetails>
</module>
And here is the code i got
private void moduleSummaryBox_SelectedIndexChanged(object sender, EventArgs e)
{
// when module from modulelist is selected, it read all indicies assigned to the module.
//!!!!!!!! it reads last node only :(? wtf im tired ...lol
//
// read data from modulelist
string path = Directory.GetCurrentDirectory();
FileStream fs = new FileStream(#"myCourse.xml", FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read);
XmlReader moduleReader = XmlReader.Create(fs);
moduleReader.Read();
while (moduleReader.Read())
{
int assessmentNo = 0;
bool match = false;
moduleReader.MoveToElement();
if (moduleReader.Name == "assessmentName")
{
moduleReader.Read();// reads xml file.
XmlNodeType nType = moduleReader.NodeType; //XmlNodeType Specifies the type of node. If node matches specified name = true.
if (nType == XmlNodeType.Text)// if node type match XmlNodeType ( and there is some text in it) statement becomes true
{
this.assno.Text = (moduleReader.Value.ToString()); //set mcode label to matched node.
}
}
if (moduleReader.Value.ToString() == moduleSummaryBox.Items[moduleSummaryBox.SelectedIndex].ToString())
{
match = true;
}
if (match == true)
{
break;
}
}
}
Help appreciated thank you :)
EDIT:
This is what goes into listbox
moduleSummaryBox.Items.Clear();
XmlDocument doc = new XmlDocument();
doc.Load(#"myCourse.xml");
XmlNodeList levelList = doc.GetElementsByTagName("level"+l_level);
foreach (XmlNode node in levelList)
{
XmlElement moduleElement = (XmlElement)node;
XmlNodeList modules_individ = moduleElement.GetElementsByTagName("module");
foreach (XmlNode nodes in modules_individ)
{
XmlElement moduleSeperator = (XmlElement)nodes;
string ll_moduleCode = moduleSeperator.GetElementsByTagName("moduleCode")[0].InnerText;
string ll_moduleTitle = moduleSeperator.GetElementsByTagName("moduleTitle")[0].InnerText;
moduleSummaryBox.Items.Add(ll_moduleCode+" : " + ll_moduleTitle+" ");
}
}
Can you Try With the code sample below:-
const string xmlString =
"<module><moduleCode>ECWM618</moduleCode><moduleTitle>Semantic and Social Web</moduleTitle><credits>15</credits>" +
"<semester>2</semester><assessmentDetails><assessment><assessmentName>Coursework1</assessmentName><assessmentType>Coursework</assessmentType>" +
"<assessmentWeighting>25</assessmentWeighting></assessment><assessment><assessmentName>Coursework2</assessmentName><assessmentType>Coursework</assessmentType>" +
"<assessmentWeighting>25</assessmentWeighting></assessment><assessment><assessmentName>Exam</assessmentName><assessmentType>Exam</assessmentType><assessmentWeighting>50</assessmentWeighting></assessment></assessmentDetails></module>";
var xml = XElement.Parse(xmlString);
var qry =
xml.Descendants()
.Where(e => e.Name == "moduleCode" && e.Value == "ECWM618")
.Ancestors()
.Descendants()
.Where(e => e.Name == "assessmentDetails")
.Elements("assessment").Count();

Categories

Resources