提问人:user2027571 提问时间:2/14/2023 最后编辑:user2027571 更新时间:2/14/2023 访问量:74
在 C# 中使用 LINQ 在运行时更改 XElement 的默认值
Change the default value of XElement at runtime in C# using LINQ
问:
如何使用 LINQ 在 C# 中更改以下 XElement 的默认值:
<Automobile>
<MainBlock>Car</MainBlock>
<Name>Audi</Name>
<Value> type="System.Double" min="0" max="100" default="50" resolution="1.0" unit=""</Value>
</Automobile>
默认值为 50。我想把它改成 20。
答:
1赞
Frenchy
2/14/2023
#1
你有很多解决方案可以做到这一点。一种解决方案:
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(@"
<Automobile>
<MainBlock>Car</MainBlock>
<Name>Audi</Name>
<Value type=""System.Double"" min=""0"" max=""100"" default=""50"" resolution=""1.0"" unit=""""></Value>
</Automobile>");
XmlNode sNode = xmldoc.SelectSingleNode("/Automobile/Value");
XmlAttribute defautAttribute = sNode.Attributes["default"];
if(defautAttribute != null)
defautAttribute.Value = "20";
评论
0赞
user2027571
2/14/2023
谢谢。有没有办法使用 LINQ 做到这一点?
0赞
Frenchy
2/14/2023
没有纯 LINQ,但您可以使用 LINQ to XML
0赞
Yitzhak Khabinsky
2/14/2023
#2
下面是一个 LINQ to XML 实现。
c#
void Main()
{
XDocument xdoc = XDocument.Parse(@"<Automobile>
<MainBlock>Car</MainBlock>
<Name>Audi</Name>
<Value type='System.Double' min='0' max='100' default='50'></Value>
</Automobile>");
xdoc.Element("Automobile").Element("Value").Attribute("default").SetValue("20");
}
评论