【问题标题】:how to parse xml , linq c#如何解析xml,linq c#
【发布时间】:2015-04-17 19:09:54
【问题描述】:

我正在尝试如下加载 xml 文件并读取每个元素的值,但结果计数始终 = 零,在我的带有代码的 xml 示例下方

1) 我的 xml 是:

<ROOT xmlns="authenticateUser">
<PARTYCODE></PARTYCODE>
<VRETCODE>10</VRETCODE>
<PRETCODE>10</PRETCODE>
<VRETERR>Incorrect user name or password entered.</VRETERR>
</ROOT>

2) 我的代码是:

 XDocument Doc = XDocument.Parse(strFileData);
                    var Result = (from Root in Doc.Descendants("ROOT")
                                  select new
                                  {
                                      PARTYCODE = Root.Element("PARTYCODE").Value ?? string.Empty,
                                      VRETCODE = Root.Element("VRETCODE").Value ?? string.Empty,
                                      PRETCODE = Root.Element("PRETCODE").Value ?? string.Empty,
                                      VRETERR = Root.Element("VRETERR").Value ?? string.Empty,
                                  }).ToList();

【问题讨论】:

标签: c# xml linq parsing


【解决方案1】:

ROOT 和所有子元素都在命名空间 authenticateUser 中,这要归功于 xmlns="authenticateUser" 默认命名空间属性。所以你需要查询元素本地名称加上命名空间名称,可以使用XName.Get(string, string)构造。

    XDocument Doc = XDocument.Parse(strFileData);
    var Result = (from Root in Doc.Descendants(XName.Get("ROOT", "authenticateUser"))
                  select new
                  {
                      PARTYCODE = Root.Element(XName.Get("PARTYCODE", "authenticateUser")).Value ?? string.Empty,
                      VRETCODE = Root.Element(XName.Get("VRETCODE", "authenticateUser")).Value ?? string.Empty,
                      PRETCODE = Root.Element(XName.Get("PRETCODE", "authenticateUser")).Value ?? string.Empty,
                      VRETERR = Root.Element(XName.Get("VRETERR", "authenticateUser")).Value ?? string.Empty,
                  }).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-06
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多