【问题标题】:how to remove xml tags for a serialized xml string如何删除序列化 xml 字符串的 xml 标签
【发布时间】:2014-11-26 19:09:02
【问题描述】:

我有一个简单的方法,它使用 C# .Net 类将对象列表序列化为 XML 字符串。对于该方法,我想从生成的 XML 字符串中删除 xml 元素。请帮忙。谢谢。

我的方法:

  public static string CreateXML(List<Video> list)
        {
            string result = "";
            StringWriter stringWriter = new StringWriter();
            XmlSerializer s = new XmlSerializer(list.GetType());
            s.Serialize(stringWriter, list);

            result = stringWriter.ToString();

            return result;
        }

我从那个方法得到的结果字符串(为简洁起见,我删掉了):

 <?xml version="1.0" encoding="utf-16" ?> 
 <ArrayOfVideo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

    <Video>- 
         ....
     </Video>

     <Video>
       ....
     </Video>

  </ArrayOfVideo>

我想要一个结果 xml 字符串,例如:(添加标签 &lt;Videos&gt; and &lt;/Videos&gt;

<Videos>
    <Video>- 
             ....
         </Video>

         <Video>
           ....
         </Video>
</Videos>

所以,我想删除行:

<?xml version="1.0" encoding="utf-16" ?> 
<ArrayOfVideo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
</ArrayOfVideo>

【问题讨论】:

  • 看看这个SO post是否有帮助。

标签: c# xml-serialization


【解决方案1】:

您可以使用 LINQ to XML 轻松解析文档并创建一个名为“Videos”的新 XElement,其中包含来自加载和解析的文档的“Video”元素。这可以用 LINQ to XML 分两行完成。

XElement element1 = XElement.Load("Videos.xml");

XElement element2 = new XElement ("Videos", element1.Elements("Video"));

【讨论】:

  • @Efstahios,感谢您的回答。但是我的方法需要将 List
  • 可能重复的问题。去这里:stackoverflow.com/questions/1772004/…
猜你喜欢
  • 2020-11-23
  • 2012-02-08
  • 2018-08-31
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
相关资源
最近更新 更多