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

本文关键字:获取 xml 参数 字符串 | 更新日期: 2023-09-27 17:56:01

我在字符串变量中有以下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>

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

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

例如

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

这是我如何反序列化它 -

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

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

然后可以像

var firstName = person.FirstName;
var lastName = person.LastName;

在 MSDN 上

使用 XmlReader 解析 XML

但是,如果您在类强类型中具有此结构,则还可以看到有关如何将其转换为XML并返回的答案:发送 XML 字符串作为响应

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

这就是你要找的。

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

希望对:)有所帮助

相关文章: