在 c# 中的 xml 中获取 xsi:type 下的节点
get a node under a xsi:type in xml in c#
我有一个 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>
我想更改 xsi:type="SecondElement"
下 Description Node
的 InnerText
当我尝试获取命名空间的属性值时
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"
你能建议我应该如何前进吗?
谢谢
使用 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");
}
}
}
我有一个 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>
我想更改 xsi:type="SecondElement"
Description Node
的 InnerText
当我尝试获取命名空间的属性值时
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"
你能建议我应该如何前进吗?
谢谢
使用 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");
}
}
}