我需要将 XDocument 中的所有值都设为小写。这样做的最佳方法是什么?
为了澄清,我想更改所有文本值,而不指定任何节点的名称。
您还可以执行以下操作:
doc.Document
.DescendantNodes()
.OfType<XText>()
.ToList().ForEach(x => x.Value = x.Value.ToLower());
我设法用 XPath 做到了:
using System.Xml.XPath;
foreach (XText text in (IEnumerable)xdoc.XPathEvaluate("//*/text()"))
{
text.Value = text.Value.ToLower();
}
下面的示例将解决问题
strxml =" <cars><name><ford>model1</ford>TEXTVALUE<renault>MODEL2</renault></name></cars>"
XDocument objDocument = XDocument.Parse(strxml);
var varNodeType = objDocument.
DescendantNodes().
Where(x => x.NodeType == XmlNodeType.Text);
foreach (var objSubType in varNodeType)
{
((System.Xml.Linq.XText)(objSubType)).Value = ((System.Xml.Linq.XText)(objSubType)).Value.ToLower();
}
甚至可以更改属性文本,以 XML 为例...
string @xml = @"<X:NOTE xmlns:X='http://www.w3.org/1999/xhtml'>
<TO>TOVE</TO>
<FROM>JANI</FROM>
<HEADING>REMINDER</HEADING>
<BODY>DON'T FORGET ME THIS WEEKEND!</BODY>
</X:NOTE>";
var xml2 = XDocument.Parse(xml);
var nodes = xml2.DescendantNodes();
foreach (XNode node in nodes)
{
XText text = node as XText;
if (text != null)
{
text.Value = text.Value.ToLower();
}
else
{
// This part if you want to ToLower attributes' values
XElement element = node as XElement;
if (element != null)
{
foreach (XAttribute attr in element.Attributes())
{
attr.Value = attr.Value.ToLower();
}
}
}
}
Console.WriteLine(xml2);