【问题标题】:Issues Querying XML with Namespace使用命名空间查询 XML 的问题
【发布时间】:2015-02-06 18:41:33
【问题描述】:

我正在尝试使用返回 XML 响应的 Rest 服务。我已成功发出获取请求,我的问题是处理响应。响应包含一个名称空间,该名称空间似乎弄乱了我的 linq 查询。我已经尝试了几乎所有我能想到的用户名总是空的。任何帮助将不胜感激,并可能挽救我的理智。

<?xml version="1.0" encoding="UTF-8"?>
<tsResponse xmlns="http://tableausoftware.com/api" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableausoftware.com/api http://tableausoftware.com/api/ts-api-2.0.xsd">
  <users>
    <user id="c9274ce9-0daa-4aad-9bd2-3b1d6d402119" name="_DevITTemplate" role="Unlicensed" publish="false" contentAdmin="false" lastLogin="" externalAuthUserId=""/>
string usersList =
request.DownloadString("http://bshagena-sandbox/api/2.0/sites/b4126fe9-d7ee-4083-88f9-                     a5eea1f40416/users/");  
request.Dispose();

XDocument xd;
XElement users;
XNamespace ns = "http://tableausoftware.com/api";

xd = XDocument.Parse(usersList);
users = xd.Root.Elements().First();

var userNames = from a in users.Descendants(ns +"users")
             select    (string)a.Attribute("name").Value;

【问题讨论】:

    标签: c# xml namespaces


    【解决方案1】:

    这就是我所做的,它似乎有效。对不起所有的cmets。我确信这不是最有效的方法。我希望这可以帮助其他人在同一问题上失去理智。

    // Sends get request and stores response as a string
    string usersList =
    request.DownloadString("http://<serverName>/api/2.0/sites/b4126fe9-d7ee-4083-88f9-a5eea1f40416/users/");  
    // declares an XML document object 
    XDocument xd;
    // Declares and XML element object
    XElement users;
    // Declares a stupid XML namespace object 
    XNamespace ns = "http://tableausoftware.com/api";
    // Sets document to value of string 
    xd = XDocument.Parse(usersList);
    // Sets the element to value of the first node of the xml document
    users = xd.Root.Elements().First();
    // Creates an array and queries elements based on attribute of name
    var userNames = from a in users.Elements(ns + "user")
                 select    (string)a.Attribute("name").Value;
    

    【讨论】:

      【解决方案2】:

      这是您的 user 元素包含属性 name,而不是 names 包装元素。相应地调整您的 xpath:(您可以使用 XNamespace)

      var userNames = from a in users.Descendants(ns + "user")
                      select a.Attribute("name").Value;        
      

      次要 - Attribute.Value 是 already a string - 无需转换 :)

      【讨论】:

      • 感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-04
      • 1970-01-01
      相关资源
      最近更新 更多