0

我有一个 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 的最佳方式是什么?我觉得有一种更简单的方法可以做到这一点。例如,我确信有一种方法可以消除多次选择单个节点的需要(我目前正在做的事情)。大家有什么推荐的?什么是最好的方法?

4

1 回答 1

1

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

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这是另一种选择。

于 2012-09-05T15:53:44.630 回答