【问题标题】:How do I parse this xml?我如何解析这个xml?
【发布时间】:2011-05-05 10:08:20
【问题描述】:

我需要使用 system.xml 在 c# 中解析以下 xml 代码。我需要一个包含用户标签内容的字符串列表。

<Configuration>
   ....
   <DebugUsersMail>
     <User>bob@example.com</User>
     <User>lenny@example.com</User>
   </DebugUsersMail>
   ...
</Configuration>

【问题讨论】:

标签: c# xml parsing


【解决方案1】:

如果你可以使用 Linq,这样的东西就很好很简单

    XDocument xmlDoc = XDocument.Load("C:\\your_xml_file.xml");
    List<string> users = xmlDoc.Descendants("User").Select(xElem => (string)xElem).ToList();

您需要在 using 语句中包含对 System.Xml.Linq 的引用才能使用 XDocument 对象。

但是,这确实假定 xml 文件中没有您不希望包含在列表中的其他用户元素。

如果你想更具体,你可以这样做

List<string> users = xmlDoc.Descendants("DebugUsersMail")
                           .Descendants("User").Select(xElem => (string)xElem).ToList();

【讨论】:

  • 我在尝试编译此代码时收到以下错误消息: System.Collections.Generic.IEnumerable' 不包含“选择”的定义并且没有可以找到接受“System.Collections.Generic.IEnumerable”类型的第一个参数的扩展方法“Select”(您是否缺少 using 指令或程序集引用?)我确实引用了程序集.我使用.Net Framework 3.5。这段代码需要 4.0 版吗?
  • 看起来您在 using 语句中没有引用 Linq。尝试使用 System.Linq 添加;到你的用途。它应该在 3.5 上正常工作,因为这就是我编译它的目的
【解决方案2】:

我找到了解决办法:

List<string> returnList = new List<string>();
XmlNodeList node = xmlDocument.GetElementsByTagName("DebugUsersMail");
XmlNodeList childNodes = node[0].ChildNodes;
for(int i = 0; i < childNodes.Count; i++)
{
   returnList.Add(childNodes[i].InnerText);
}
return returnList;

【讨论】:

    【解决方案3】:

    在 C# 中有很多方法可以做到这一点。您可以使用:

    • XmlDocument,然后是 XPath 和 XQuery
    • XDocument 和 Linq
    • XmlTextReader/SAX
    • 正则表达式
    • 将 XML 反序列化为对象

    采取的路线很大程度上取决于 XML 的其余部分是什么样的。

    【讨论】:

    • System.xml 包含以上所有内容。
    • @Luke:你试过什么?您是否阅读过关于 system.xml 的 MSDN 文档?
    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2013-06-07
    • 2013-06-09
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多