【问题标题】:Is there a way to read the name of the main xml tag in C#?有没有办法在 C# 中读取主要 xml 标签的名称?
【发布时间】:2020-09-24 14:52:08
【问题描述】:

我有 2 个 xml 文件:

<?xml version="1.0" encoding="UTF-8"?>
<abc300:TEST xmlns:iabc="http://www.isa.com/iabc/1_0/basic/schema" xmlns:abc300="http://www.isa.com/iabc/1_0/abc300/schema" >
        <abc300:Header>
            <abc300:AbcCode>111</abc300:AbcCode>
        </abc300:Header>
</abc300:TEST>

<?xml version="1.0" encoding="UTF-8"?>
<abc301:TEST xmlns:iabc="http://www.isa.com/iabc/1_0/basic/schema" xmlns:abc300="http://www.isa.com/iabc/1_0/abc301/schema" >
    <abc301:Header>
        <abc301:AbcCode>111</abc301:AbcCode>
    </abc301:Header>
</abc301:TEST>

我想知道是否有办法通过 C# 获取 abc300abc301 名称标签,因此我可以(通过程序)查看用户使用的 xml 文件. 已经谢谢了。

【问题讨论】:

  • 请注意,这不是元素的名称——它是元素的 namespace 的别名。你有没有尝试过什么?例如,在 LINQ to XML 中获取实际的命名空间(例如“isa.com/iabc/1_0/abc301/schema"”)应该相当容易。
  • 对此有很多疑问;你看过他们中的任何一个吗?例如,XML Element and NamespaceHow do I get the XML root node with C#?
  • 是的,我尝试了很多,但没有奏效。另外上面的链接我仍然没有得到别名。如果我使用以下代码: var test = _vm.XmlDoc.DocumentElement; var t2 = test.Attributes; t2 回馈了一些属性,但我仍然不知道如何获取别名“abc300”或“abc301”

标签: c# xml


【解决方案1】:

使用 Xml Linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;


namespace ConsoleApplication170
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            string rootStr = doc.Root.Name.LocalName;
            XElement root = doc.Root;
            XNamespace ns = root.Name.Namespace;
            string prefix = root.GetPrefixOfNamespace(ns);
        }
    }
}

【讨论】:

  • 谢谢,我不知道这是可能的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 2019-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多