【问题标题】:XMLString needs to change the formatXMLString 需要改变格式
【发布时间】:2012-03-02 18:07:12
【问题描述】:

我的 xml 数据是这样的:(这是 xmlstring 不是 xmlfile,我需要在不保存的情况下进行转换......)

 <ProductGroups>
 <ProductGroup>
 <Name>ABC</Name>
 <Id>123</Id>
 </ProductGroup>
 <ProductGroup>
 <Name >xyz</Name>
 <Id>456</Id>
 </ProductGroup>
 <ProductGroup>
 <Name>PQR</Name>
 <Id>789</Id>
 </ProductGroup>
     .
     .
 </ProductGroups>

我想这样变身

<PRODUCTGROUPS>
<Name ID="123"> ABC</NAME>
<Name ID="456"> XYZ</NAME>
<Name ID="789">PQR</NAME>
   .
   .
</PRODUCTGROUPS>

我将 C# 与 .NET 结合使用。

【问题讨论】:

  • 你试过什么?如果您想转换 XML,您是否考虑过 XSLT(可扩展样式表语言转换)?
  • 请不要将ProductGroups 转换为PRODUCTGROUPS
  • 你在纠结哪一点?
  • @Henk Holterman:这似乎是用户倾向于随机切换到大写字母的产物。请参阅原始修订。不过,好电话。
  • @Henk Holterman:我不会将 ProductGroups 更改为 PRODUCTGROUPS。感谢您的宝贵建议。

标签: c# .net xml xml-parsing


【解决方案1】:

凭记忆,可能包含一些错误:

var doc = XDocument.Load(...);
var groups = doc.Descendants(ProductGroup);

var newDoc = new XElement("ProductGroups", 
    groups.Select(pg => new XElement("Name", 
            new XAttribute("Id", pg.Element("Id").Value), 
            pg.Element("Name").Value) ));


newDoc.Save(...);

【讨论】:

  • @melanie:当你有一个 XML string 时,使用XDocument.Parse(str)。加载用于文件或 URL。
【解决方案2】:

您可以使用 linq2xml 进行尝试:(编辑:与 Henk Holterman 大致相同的方法)

XDocument sourceDocument = XDocument.Load("D:\\XmlFile.xml");

XDocument targetDocument = new XDocument();
var productGroupsElement = new XElement("ProductGroups");
sourceDocument.Descendants("ProductGroup").ToList().ForEach(productGroup =>
{
    if (productGroup.Element("Name") != null && productGroup.Element("Id") != null)
    {
        var nameElement = new XElement("Name", productGroup.Element("Name").Value);
        nameElement.Add(new XAttribute("Id", productGroup.Element("Id")));
        productGroupsElement.Add(nameElement);
    }
});

targetDocument.Add(productGroupsElement);
var resultXml = targetDocument.ToString(SaveOptions.None);

【讨论】:

  • XDocument sourceDocument = XDocument.Load(ReturnXml); SOURCEDOCUMENT 保持为空!!!
  • 如果您在磁盘上放入字符串而不是文件,请使用 XDocument.Parse(ReturnXml);
  • 从 ppl 为您编写的代码中学习也是明智的,而不是仅仅粘贴它并朝着您遇到的下一个“问题”前进。通过研究代码,您可以很容易地自己弄清楚这一点,同时 XDocument 上的 Load 和 Parse 方法得到了很好的注释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
相关资源
最近更新 更多