Reputation: 1174
I have following xml in string variable-
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<first-name>RaJeEv(๏๏)</first-name>
<last-name>Diboliya</last-name>
<headline>Software Engineer at FASTTRACK INDIA.</headline>
<site-standard-profile-request>
<url>http://www.linkedin.com/profile?viewProfile=&url>
</site-standard-profile-request>
</person>
Now I want to get first and last name from this string. How can I do this?
Upvotes: 2
Views: 1168
Reputation: 1896
This is what you are looking for..
XmlDocument xmldoc = new XmlDocument();
XmlNodeList xmlnode;
FileStream fs = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName("first-name");
string firstname= string.Empty;
if(xmlnode!=null)
strOption = Regex.Replace(xmlnode[0].InnerText, @"\t|\n|\r| ", "");
xmlnode = xmldoc.GetElementsByTagName("last-name");
string lastname= string.Empty;
if(xmlnode!=null)
strOption = Regex.Replace(xmlnode[0].InnerText, @"\t|\n|\r| ", "");
Hope it helps :)
Upvotes: 0
Reputation: 1370
var person = XElement.Parse(yourString).Element("person");
string firstName = person.Element("first-name").Value;
string lastName = person.Element("last-name").Value;
Upvotes: 0
Reputation: 9049
Here's how I would deserialize this -
Create a concrete domain class Person
[Serializable()]
public class Person
{
[System.Xml.Serialization.XmlElementAttribute("first-name")]
public string FirstName{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("last-name")]
public string LastName{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("headline")]
public string Headline{ get; set; }
[System.Xml.Serialization.XmlElementAttribute("site-standard-profile-request")]
public string ProfileRequest{ get; set; }
}
The use XmlSerializer to convert it to Person type
XmlSerializer serializer = new XmlSerializer(typeof(Person));
var person = serializer.Deserialize(xml) as Person;
The properties can then be accessed like
var firstName = person.FirstName;
var lastName = person.LastName;
Upvotes: 2
Reputation: 7800
for example
public class Program {
public static void Main(String[] args) {
XDocument xdoc = XDocument.Parse(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<person>
<first-name>RaJeEv(๏๏)</first-name>
<last-name>Diboliya</last-name>
<headline>Software Engineer at FASTTRACK INDIA.</headline>
<site-standard-profile-request>
<url>http://www.linkedin.com/profile?viewProfile</url>
</site-standard-profile-request>
</person>");
XElement xe = xdoc.Elements("person").First();
Console.WriteLine("{0} {1}", xe.Element("first-name").Value, xe.Element("last-name").Value);
}
}
Upvotes: 2
Reputation: 66641
Right on the MSDN
but if you have this struct in a class strong type you can also see this answer on how you convert it to xml and back: Send XML String as Response
Upvotes: 0