【问题标题】:Extract data from the XML in C#在 C# 中从 XML 中提取数据
【发布时间】:2016-12-23 03:18:48
【问题描述】:

我在 C# 中有字符串,它具有以下内容

  responseString = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<lab:labs xmlns:lab=\"http://njjhjhjh/ri/lab\">\n    <lab uri=\"https://dsdsdsds.org/api/v2/labs/1\">\n        <name>Administrative Lab</name>\n    </lab>\n</lab:labs>\n"

我希望将 uri 值 https://dsdsdsds.org/api/v2/labs/1 提取并存储在字符串中

           string xmlString =responseString.Replace("lab:labs>", "labs>");
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xmlString);
            XmlNodeList nodes = doc.SelectNodes("labs//lab");
            if (nodes != null && nodes.Count > 0)
            {
                XmlNode node = nodes[0];
                if (node.Attributes["uri"] != null)
                {
                    string return_uri = node.Attributes["uri"].Value.ToString();

                }
            }

但上面的代码会抛出类似{"The 'lab:labs' start tag on line 2 position 2 does not match the end tag of 'labs'. Line 6, position 3."} 的错误。有没有一种简单的方法来获取该 uri 值

【问题讨论】:

  • 那是因为您正在破坏您的 XML。不要那样做;相反,请正确使用命名空间。
  • 另外,使用XDocument;好多了。

标签: c# xml xml-parsing


【解决方案1】:

试试这个..

var doc = XDocument.Parse(responseString);
var result = doc.Descendants().First(d => d.Name=="lab").Attribute("uri").Value;

【讨论】:

    【解决方案2】:

    这可能对你有用

    var urival = xdoc.Descendants("lab").Attributes("uri");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多