c# - XML 字符串到 XML 文档

标签 c# xml

我在 String 中有一个完整的 XML 文档,我需要将其转换为 XML 文档并解析文档中的标签

最佳答案

此代码示例取自 csharp-examples.net , 由 Jan Slama 撰写:

To find nodes in an XML file you can use XPath expressions. Method XmlNode.Selec­tNodes returns a list of nodes selected by the XPath string. Method XmlNode.Selec­tSingleNode finds the first node that matches the XPath string.

XML:

<Names>
    <Name>
        <FirstName>John</FirstName>
        <LastName>Smith</LastName>
    </Name>
    <Name>
        <FirstName>James</FirstName>
        <LastName>White</LastName>
    </Name>
</Names>

代码:

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"

XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
  string firstName = xn["FirstName"].InnerText;
  string lastName = xn["LastName"].InnerText;
  Console.WriteLine("Name: {0} {1}", firstName, lastName);
}

关于c# - XML 字符串到 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6402596/

相关文章:

c# - 如何在c#中将json转换为json对象?

c# - 查询优化或在 ViewModel 中的 DoWork 内缓慢填充 ObservableObject

Java正则表达式多个标签和属性

java - 在循环中使用 XPath 表达式

c# - 你能有 2 个 url 指向 asp :Menu control? 中的同一页面吗

c# - 如何使用 C# 互操作传递 dbFailOnError 参数?

c# - HTML Agility Pack W3C 工具的问题

Android 样式资源编译 (aapt) 失败 : Bad resource table: header size 0xc

php - file_get_contents() 移除 XML 标签

android - 创建 xml android 布局的多个实例