How to retrieve data from an XML file in a Sharepo

2019-08-01 03:10发布

问题:

I am following this tutorial and I am trying to setup the code in a Event Receiver.

I need 2 properties to send into their method a SPWeb and string.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    // is there a way to make this non hardcoded? 
    SPSite site = new SPSite("http://localhost.com");
    SPWeb web = site.OpenWeb("/");
    string XMlPath = // get xml file path
    CreateGroups(web, path);
}

private void CreateGroups(SPWeb currentSite, string groupsFilename)
{

}

So I tried to use getFullPath but that did not work. I also tried to use MapPath but I did not seem to have access to that.

So how do I get XML file (I think thats what I need)?

回答1:

  1. You need to dispose of the SPSite / SPWeb object, this is usually done in a using clause.
  2. You don't need to use an absolute path (hard code) in a feature receiver, as the feature is already web/site scoped
  3. your XmlPath usually needs to point to a file on the Sharepoint server, which you also deployed in your Feature - as the feature receiver is running after all the normal files have been deployed, you're good.

Without further ado, slightly different code:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    //Web scoped feature?
    //spWeb = (SPWeb) properties.Feature.Parent;
    //assuming Site scoped feature
    spWeb = ((SPSite) properties.Feature.Parent).RootWeb;

    using (spWeb)
    {
        string XmlPath = properties.Definition.RootDirectory + @"\Xmlfile\groups.xml"
        CreateGroups(spWeb, XmlPath);
    }
}

So how do you get your XML file into "\Xmlfile\groups.xml"? Just create a module! (Add new item > Module) The elements.xml of your module should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <Module Name="Xmlfile" Path="Xmlfile">
        <File Path="groups.xml" Url="Xmlfile/groups.xml" />
    </Module>
</Elements>

Of course you will need to add your groups.xml file into that module (Context menu > Add existing item) for this to work.
Also note that you can easily debug feature receivers, just make sure that the deployment configuration is set to "No Activation" (Project Properties > Sharepoint > Active Deployment Configuration) - this way you will need to manually activate the feature on the site (instead of Visual Studio doing it automatically for you in debug mode) - but debugging will work flawlessly.