简体   繁体   English

使用c#修剪() xml文档中所有xml元素和属性的值

[英]Trim() the values of all xml elements and attributes in an xml document using c#

I'm trying to figure out the simplest way to take xml like this:我试图找出像这样使用 xml 的最简单方法:

<Car>
 <Description Model="Ford      ">Blue     </Description>
</Car>

into this:进入这个:

<Car>
  <Description Model="Ford">Blue</Description>
</Car>

Using LINQ to XML, how about something like:使用 LINQ to XML,怎么样:

foreach (var element in doc.Descendants())
{
    foreach (var attribute in element.Attributes())
    {
        attribute.Value = attribute.Value.Trim();
    }
    foreach (var textNode in element.Nodes().OfType<XText>())
    {
        textNode.Value = textNode.Value.Trim();
    }    
}

I think that should work... I don't believe you need to use ToList to avoid disturbing things as you iterate, as you're not changing the structure of the XML document, just the text.认为这应该有效...我不认为您需要使用ToList来避免在迭代时产生干扰,因为您不会更改 XML 文档的结构,而只是更改文本。

Try this.试试这个。 Don't forget to recurse through your ChildNodes ...不要忘记通过你的子节点递归......

protected void Page_Load(object sender, EventArgs e)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(@"c:\temp\cars.xml");
    Recurse(doc.ChildNodes);
}
private void Recurse(XmlNodeList nodes)
{
    foreach (XmlNode node in nodes)
    {
        if (node.InnerText != null)
            node.InnerText = node.InnerText.Trim();

        if (node.Attributes != null)
        {
            foreach (XmlAttribute att in node.Attributes)
                att.Value = att.Value.Trim();
        }

        Recurse(node.ChildNodes);
    }
}

If you're not using or can't use LINQ to XML then the below worked well for me with XmlDocument如果您不使用或不能使用 LINQ to XML,那么下面的 XmlDocument 对我来说效果很好

TrimXmlText(xmlDocument.ChildNodes);

private void TrimXmlText(XmlNodeList xmlNodeList)
{
    foreach (XmlNode xmlNode in xmlNodeList)
    {
        if (xmlNode.NodeType == XmlNodeType.Text)
        {
            xmlNode.InnerText = xmlNode.InnerText?.Trim();
        }
        else
        {
            TrimXmlText(xmlNode.ChildNodes);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM