检查在base64中编码的XML附件的大小

时间:2017-11-20 14:24:51

标签: c# xml

我正在遍历包含许多XML文件的列表,每个文件都附加了各种文件,以base64编码。附件模板:

        <my:Attachments>
        <my:Attachment-name>base64code</my:Attachment-name>
        <my:Attachment-name-Description/>
        <my:Attachment-name2>base64code</my:Attachment-name2>
        <my:Attachment-Checklist-Description/>
        <my:Additional-Attachments>
            <my:Attachment>base64code</my:Attachment>
            <my:Attachment-Description>description</my:Attachment-Description>
        </my:Additional-Attachments>
        <my:Additional-Attachments>
            <my:Attachment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">base64code</my:Attachment>
            <my:Attachment-Description>description2</my:Attachment-Description>
        </my:Additional-Attachments>
    </my:Attachments>

我的目标是检查所有文件中的附件数量以及尺寸大于提供的附件数量。

我在c#中这样做,我一直在努力挖掘xml文件本身。有什么建议我如何迭代编码成xml的附件,并检查它们在base64中的大小?

更新

根据daniell89的建议,我这样做了:

                    foreach (Microsoft.SharePoint.Client.File file in fileCollection)
                {
                    FileInformation fileInformation =
                        Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
                    using (StreamReader streamReader = new StreamReader(fileInformation.Stream))
                    {
                        XDocument xmlDocument = XDocument.Load(streamReader);
                        XNamespace my =
                            XNamespace.Get(
                                "http://schemas.microsoft.com/office/infopath/2003/myXSD/2011-05-03T19:16:34");

                        foreach (XElement xe in xmlDocument.Descendants(my + "Attachments"))
                        {

                        }
                    }
                }

由于附件节点中的每个元素都有不同的名称,我试图遍历所有这些元素,如果它的值有base64,那么完成剩下的工作。问题是,而不是每个行的集合,我得到1项由我的所有行组成:附件

1 个答案:

答案 0 :(得分:1)

您可以将XDocument类和Linq用于xml。这是一个例子:

string xmlData = "yourXmlString";
int maxAttachementSize = 100000;
XDocument xml = XDocument.Parse(xmlData);
XNamespace my_ns = "myNamespaceDefinition";
var attachementsInBase64String = xml.Descendants(my_ns + "Attachment").Select(x => x.Value);
var tooBigAttachements = attachementsInBase64String .Where(att => Convert.FromBase64String(att).Length > maxAttachementSize);

根据您的更新,您可以通过这种方式检查附件(假设您有一个Attachements元素):

foreach (XElement xElem in xDoc.Element("Attachments").Descendants().Where(e => !e.HasElements))
{
      if(!string.IsNullOrWhiteSpace(xElem.Value))
      {
           byte[] attachement = Convert.FromBase64String(xElem.Value);
           // rest of a code
      }
} 
相关问题