3

Analyze optional tags in C #

 3 years ago
source link: https://www.codesd.com/item/analyze-optional-tags-in-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Analyze optional tags in C #

advertisements

I'm trying to find an easy and slick way to do the following requirement.

I have a XML message with this arrangement:

  <persons>
    <person>
       <firstName>Mike</firstName>
       <middleName>K.</middleName>
       <lastName>Kelly</lastName>
    </person>
    <person>
       <firstName>Steve</firstName>
       <lastName>David</lastName>
    </person>
    <person>
       <firstName>Laura</firstName>
       <middleName>X.</middleName>
       <lastName>Xavier</lastName>
    </person>
  </persons>

I want to parse this XML using xPath expressions.

persons/person/firstName
persons/person/middleName
persons/person/lastName

My objective is store firstName, middleName and lastName tag values like this into a list of string objects like this:

firstNameList[0] = "Mike";
firstNameList[1] = "Steve";
firstNameList[2] = "Laura";

middleNameList[0] = "K.";
middleNameList[1] = null;
middleNameList[2] = "X.";

lastNameList[0] = "Kelly";
lastNameList[1] = "David";
lastNameList[2] = "Xavier";

In my C# code, I do this:

XmlNodeList firstNameNodeList = xmlDoc.SelectNodes("persons/person/firstName", nsmgr);
XmlNodeList middleNameNodeList = xmlDoc.SelectNodes("persons/person/middleName", nsmgr);
XmlNodeList lastNameNodeList = xmlDoc.SelectNodes("persons/person/lastName", nsmgr);

The problem with this code is that for middle name, I don't have it for 2nd person in my XML list. So the middleNameNodeList returns 2 values (K. and X.) but I wouldn't know whether the 1st or 2nd or 3rd person's middle name is missing.

I was hoping that SelectNodes() API would provide an iteration or index ID as which repeating element has a given value.

Please suggest me an easiest way to achieve what I needed? Thanks so much for your help, JK


How about this?

foreach (Node person in xmlDoc.SelectNodes("persons/person", nsmgr))
{
    firstNameNodeList.Add(person.SelectSingleNode("firstName", nsmgr));
    middleNameNodeList.Add(person.SelectSingleNode("middleName", nsmgr));
    lastNameNodeList.Add(person.SelectSingleNode("lastName", nsmgr));
}




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK