想从字符串参数中获取xml值

时间:2013-01-24 08:32:33

标签: c# asp.net xml string

我在字符串变量中有以下xml -

    <?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=&amp;url>
  </site-standard-profile-request>
</person>

现在我想从这个字符串中获取名字和姓氏。我怎么能这样做?

5 个答案:

答案 0 :(得分:2)

例如

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);
    }         
}

答案 1 :(得分:2)

以下是我将反序列化的方法 -

创建具体的域类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; }
}

使用XmlSerializer将其转换为Person type

XmlSerializer serializer = new XmlSerializer(typeof(Person));
var person = serializer.Deserialize(xml) as Person;

然后可以像

一样访问属性
var firstName = person.FirstName;
var lastName = person.LastName;

答案 2 :(得分:0)

在MSDN上正确

Parse XML with XmlReader

但是如果你在类强类型中有这个结构,你也可以看到关于如何将它转换为xml并返回的答案: Send XML String as Response

答案 3 :(得分:0)

var person = XElement.Parse(yourString).Element("person");
string firstName = person.Element("first-name").Value;
string lastName = person.Element("last-name").Value;

答案 4 :(得分:0)

这就是你要找的......

        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| ", "");

希望有所帮助:)