2

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

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

4

5 回答 5

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);
    }         
}
于 2013-01-24T08:42:30.233 回答
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 类型

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

然后可以像这样访问属性

var firstName = person.FirstName;
var lastName = person.LastName;
于 2013-01-24T08:42:53.647 回答
0

就在 MSDN 上

使用 XmlReader 解析 XML

但是,如果您在类强类型中有此结构,您还可以看到有关如何将其转换为 xml 并返回的答案: Send XML String as Response

于 2013-01-24T08:41:44.780 回答
0
var person = XElement.Parse(yourString).Element("person");
string firstName = person.Element("first-name").Value;
string lastName = person.Element("last-name").Value;
于 2013-01-24T08:43:59.520 回答
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| ", "");

希望能帮助到你 :)

于 2013-01-24T08:48:56.530 回答