将 Linq to Xml 与 Xml 命名空间结合使用

发布于 2024-08-23 14:03:26 字数 1008 浏览 8 评论 0原文

我有这样的代码:

/*string theXml =
@"<Response xmlns=""http://myvalue.com""><Result xmlns:a=""http://schemas.datacontract.org/2004/07/My.Namespace"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:TheBool>true</a:TheBool><a:TheId>1</a:TheId></Result></Response>";*/

string theXml = @"<Response><Result><TheBool>true</TheBool><TheId>1</TheId></Result></Response>";

XDocument xmlElements = XDocument.Parse(theXml);

var elements = from data in xmlElements.Descendants("Result")
               select new {
                            TheBool = (bool)data.Element("TheBool"),
                            TheId = (int)data.Element("TheId"),
                          };

foreach (var element in elements)
{
    Console.WriteLine(element.TheBool);
    Console.WriteLine(element.TheId);
}

当我使用 theXml 的第一个值时,结果为 null,而使用第二个值时,我有很好的值...

如何将 Linq to Xml 与 xmlns 值一起使用?

I have this code :

/*string theXml =
@"<Response xmlns=""http://myvalue.com""><Result xmlns:a=""http://schemas.datacontract.org/2004/07/My.Namespace"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:TheBool>true</a:TheBool><a:TheId>1</a:TheId></Result></Response>";*/

string theXml = @"<Response><Result><TheBool>true</TheBool><TheId>1</TheId></Result></Response>";

XDocument xmlElements = XDocument.Parse(theXml);

var elements = from data in xmlElements.Descendants("Result")
               select new {
                            TheBool = (bool)data.Element("TheBool"),
                            TheId = (int)data.Element("TheId"),
                          };

foreach (var element in elements)
{
    Console.WriteLine(element.TheBool);
    Console.WriteLine(element.TheId);
}

When I use the first value for theXml, the result is null, whereas with the second one, I have good values ...

How to use Linq to Xml with xmlns values ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

横笛休吹塞上声 2024-08-30 14:03:26

DescendantsElement 等 LINQ to XML 方法采用 XName 作为参数。从 stringXName 的转换会自动为您进行。您可以通过在 DescendantsElement 调用中的字符串之前添加 XNamespace 来解决此问题。请注意,因为您有 2 个不同的命名空间在工作。


string theXml =
                @"true1";

            //string theXml = @"true1";

    XDocument xmlElements = XDocument.Parse( theXml );
    XNamespace ns = "http://myvalue.com";
    XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";
    var elements = from data in xmlElements.Descendants( ns + "Result" )
          select new
                 {
                     TheBool = (bool) data.Element( nsa + "TheBool" ),
                     TheId = (int) data.Element( nsa + "TheId" ),
                 };

    foreach ( var element in elements )
    {
        Console.WriteLine( element.TheBool );
        Console.WriteLine( element.TheId );
    }

注意在后代中使用ns和在Elements中使用nsa

LINQ to XML methods like Descendants and Element take an XName as an argument. There is a conversion from string to XName that is happening automatically for you. You can fix this by adding an XNamespace before the strings in your Descendants and Element calls. Watch out because you have 2 different namespaces at work.


string theXml =
                @"true1";

            //string theXml = @"true1";

    XDocument xmlElements = XDocument.Parse( theXml );
    XNamespace ns = "http://myvalue.com";
    XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";
    var elements = from data in xmlElements.Descendants( ns + "Result" )
          select new
                 {
                     TheBool = (bool) data.Element( nsa + "TheBool" ),
                     TheId = (int) data.Element( nsa + "TheId" ),
                 };

    foreach ( var element in elements )
    {
        Console.WriteLine( element.TheBool );
        Console.WriteLine( element.TheId );
    }

Notice the use of ns in Descendants and nsa in Elements

滥情空心 2024-08-30 14:03:26

您可以将带有命名空间的 XName 传递给后代()Element()。当您将字符串传递给 Descendants() 时,它会隐式转换为没有命名空间的 XName。

要在命名空间中创建 XName,您需要创建一个 XNamespace 并将其连接到元素 local-name(字符串)。

XNamespace ns = "http://myvalue.com";
XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";

var elements = from data in xmlElements.Descendants( ns + "Result")
                   select new
                              {
                                  TheBool = (bool)data.Element( nsa + "TheBool"),
                                  TheId = (int)data.Element( nsa + "TheId"),
                              };

还有一种简写形式,用于通过字符串的隐式转换来创建带有命名空间的 XName。

var elements = from data in xmlElements.Descendants("{http://myvalue.com}Result")
                   select new
                              {
                                  TheBool = (bool)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheBool"),
                                  TheId = (int)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheId"),
                              };

或者,您可以查询 XElement。Name.LocalName

var elements = from data in xmlElements.Descendants()
                   where data.Name.LocalName == "Result"

You can pass an XName with a namespace to Descendants() and Element(). When you pass a string to Descendants(), it is implicitly converted to an XName with no namespace.

To create a XName in a namespace, you create a XNamespace and concatenate it to the element local-name (a string).

XNamespace ns = "http://myvalue.com";
XNamespace nsa = "http://schemas.datacontract.org/2004/07/My.Namespace";

var elements = from data in xmlElements.Descendants( ns + "Result")
                   select new
                              {
                                  TheBool = (bool)data.Element( nsa + "TheBool"),
                                  TheId = (int)data.Element( nsa + "TheId"),
                              };

There is also a shorthand form for creating a XName with a namespace via implicit conversion from string.

var elements = from data in xmlElements.Descendants("{http://myvalue.com}Result")
                   select new
                              {
                                  TheBool = (bool)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheBool"),
                                  TheId = (int)data.Element("{http://schemas.datacontract.org/2004/07/My.Namespace}TheId"),
                              };

Alternatively, you could query against XElement.Name.LocalName.

var elements = from data in xmlElements.Descendants()
                   where data.Name.LocalName == "Result"
傲世九天 2024-08-30 14:03:26

我在 XML 文档的顶部列出了几个名称空间,我并不真正关心哪些元素来自哪个名称空间。我只想按元素的名称获取元素。我写了这个扩展方法。

    /// <summary>
    /// A list of XElement descendent elements with the supplied local name (ignoring any namespace), or null if the element is not found.
    /// </summary>
    public static IEnumerable<XElement> FindDescendants(this XElement likeThis, string elementName) {
        var result = likeThis.Descendants().Where(ele=>ele.Name.LocalName==elementName);
        return result;
    }

I have several namespaces listed at the top of an XML document, I don't really care about which elements are from which namespace. I just want to get the elements by their names. I've written this extension method.

    /// <summary>
    /// A list of XElement descendent elements with the supplied local name (ignoring any namespace), or null if the element is not found.
    /// </summary>
    public static IEnumerable<XElement> FindDescendants(this XElement likeThis, string elementName) {
        var result = likeThis.Descendants().Where(ele=>ele.Name.LocalName==elementName);
        return result;
    }
花间憩 2024-08-30 14:03:26

我发现以下代码可以很好地读取 VB.NET 中具有命名空间的属性:

MyXElement.Attribute(MyXElement.GetNamespaceOfPrefix("YOUR_NAMESPACE_HERE") + "YOUR_ATTRIB_NAME")

希望这对以后的人有所帮助。

I found the following code to work fine for reading attributes with namespaces in VB.NET:

MyXElement.Attribute(MyXElement.GetNamespaceOfPrefix("YOUR_NAMESPACE_HERE") + "YOUR_ATTRIB_NAME")

Hope this helps someone down the road.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文