【问题标题】:get a node under a xsi:type in xml in c#在 c# 中获取 xsi:type in xml 下的节点
【发布时间】:2017-04-27 14:36:14
【问题描述】:

我有一个格式如下的 XML 文件

<ScriptElement>
      <ElementData xsi:type="FirstElement">
         .......
         .......
         .......
         <Description></Description>
         ........ 
      </ElementData>
</ScriptElement>
<ScriptElement>
      <ElementData xsi:type="SecondElement">
         .......
         .......
         .......
         <Description></Description>
         ........ 
      </ElementData>
</ScriptElement>
<ScriptElement>
      <ElementData xsi:type="ThirdElement">
         .......
         .......
         .......
         <Description></Description>
         ........ 
      </ElementData>
</ScriptElement>

我想更改Description Node下的InnerTextxsi:type="SecondElement"

当我尝试获取命名空间的属性值时

string attrValist = Doc.SelectSingleNode("ScriptElements/ScriptElement/ElementData/@xsi:type").Value;

MessageBox.Show(attrValist);

"Namespace Manager or XsIContext needed. The query has a prefix variable or user-defined function" 出现错误

能否请您建议我应该如何前进。

谢谢

【问题讨论】:

    标签: c# system.xml


    【解决方案1】:

    使用 Xml Linq:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication50
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test2.xml";
            static void Main(string[] args)
            {
    
                XDocument doc = XDocument.Load(FILENAME);
    
                Dictionary<string, XElement> dict = doc.Descendants("ElementData").GroupBy(x => (string)x.Attributes().Where(y => y.Name.LocalName == "type").FirstOrDefault(), z => z)
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());
    
                XElement SecondElement = dict["SecondElement"];
    
                SecondElement.Element("Description").SetValue("abcd");
            }
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-12
      • 2020-06-14
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多