填充XML的正确/最佳方式是什么?

时间:2012-09-05 15:15:38

标签: c# xml

我有一个XML:

<PolicyChangeSet schemaVersion="2.1" username="" description="">
  <Note>
    <Content></Content>
  </Note>
  <Attachments>
    <Attachment name="" contentType="">
      <Description></Description>
      <Location></Location>
    </Attachment>
  </Attachments>
</PolicyChangeSet>

我有一个填充XML的方法:

public static void GeneratePayLoad(string url, string policyID)
        {
            string attachmentName = policyID.Split(new string[] { "REINSTMT" }, StringSplitOptions.None)[0] + "REINSTMT";

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(AppVars.pxCentralXMLPayloadFilePath);
            XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet");
            node.Attributes["username"].Value = AppVars.Username;
            node.Attributes["description"].Value = "Upload Documents";

            node = xmlDoc.SelectSingleNode("PolicyChangeSet/Note/Content");
            node.InnerText = "The attached pictures were sent by the producer.";

            node = xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachments/Attachment");
            node.Attributes["name"].Value = attachmentName;
            node.Attributes["contentType"].Value = "image/tiff";

            node = xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachments/Attachment/Description");
            node.InnerText = "Combined reinstatement picture file";

            node = xmlDoc.SelectSingleNode("/PolicyChangeSet/Attachments/Attachment/Location");
            node.InnerText = url;

            xmlDoc.Save(AppVars.pxCentralXMLPayloadFilePath);
        }

我的问题是,填充XML的最佳方法是什么?我觉得有一种更简单的方法。例如,我确信有一种方法可以消除多次选择单个节点的需要(我正在做的事情)。你们推荐什么?什么是最好的方式?

1 个答案:

答案 0 :(得分:1)

使用序列化/反序列化策略可能是一种选择,但有时您希望避免这种情况,如果您不想仅仅因为DTO而污染您的代码。在最后一种情况下,您可以使用已经提到的XDocument相关内容,如下所示:

var doc = XElement.Parse(
    @"<PolicyChangeSet schemaVersion='2.1' username='' description=''>
    <Note>
        <Content></Content>
    </Note>
    <Attachments>
        <Attachment name='' contentType=''>
        <Description></Description>
        <Location></Location>
        </Attachment>
    </Attachments>
    </PolicyChangeSet>");

doc.Descendants("Note")
   .Descendants("Content").First().Value = "foo";

var attachment = doc.Descendants("Attachments")
                    .Descendants("Attachment").First();

attachment.Attributes("name").First().Value = "bar";
attachment.Attributes("contentType").First().Value = "baz";

...

doc.Save(...);

您将使用Load方法而不是Parse从文件中加载xml。这是另一种选择。