jjzjj

c# - 必须在非通用静态类中定义扩展方法 - 从文档中提取 XML

coder 2024-07-03 原文

我目前正在编写一个从文档中获取 XML 并将其显示在网页上的上传系统。

我面临的问题是,每当我添加网站的 XML 提取部分时,编译器都会返回标题中提到的错误。

我的代码目前看起来像这样。

导致问题的部分是 publicstatic Xnamespace w 和以下所有相关的 XML 代码。干杯。

<script runat="server">
    //This template is being built to allow the viewstates to be displayed and allow them to be hidden
    //or shown at the same time. The buttons are being added so we can test whether they will
    //be hidden on page use


    public string _TempFileLocation = ""; //Used to locate Word Document File Path 


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {


            string viewStateDisplay1 = "ViewState1 is now being displayed";
            string viewStateDisplay2 = "ViewState2 is now being displayed";
           // var ViewShow = viewStateDisplay1;
           // var ViewShow2 = viewStateDisplay2; 

            if (ViewState["PageState"] == null)
            {
                ViewState["PageState"] = viewStateDisplay1;
            }

                else
                {
                    ViewState["PageState"] = viewStateDisplay2;
                    //viewStateDisplay = false;
                }
        }

    }

    //button that shows the label string
    protected void btnClick_Click(object sender, EventArgs e)
    {
        lblString.Text = ViewState["PageState"].ToString();
        lblString.Visible = true;
    }

    //button that hides the div, changing "lblstring" or adding more should be able to hide 
    //or show whatever methods / objects we want
    private void Close(object sender, EventArgs e)
    {
        lblString.Visible = !lblString.Visible;
        lblString.Visible = false;
    }


    //This will be the default set for the page. It will start on true for viewstatedisplay
    //this will be done again, but with viewstatedisplay2 for the next method regarding 
    //the two columns and displaying document and DB data. "viewStateDisplay2.Visible = true"

    //private void gotoviewStateDisplay1(object sender, EventArgs e)
    // {
    //   ViewState("PageState") = 1;
    //   viewStateDisplay1.Visible = true;
    //   viewStateDisplay2.Visible = false;
    //}

    //private void gotoviewStateDisplay2(object sender, EventArgs e)
    // {
    //   ViewState("PageState") = 2;
    //   viewStateDisplay1.Visible = false;
    //   viewStateDisplay2.Visible = true;
    //}




    //THE USER UPLOAD CONTROL. users use this to upload the document to the server
    //This has validation so they cannot upload wrong file types / too large files

   // public partial class UploadFileControl : System.Web.UI.UserControl
  //  {

        //ViewState1 

        public void XMLextractor(string _filePath)
        {

            //XML extraction code
           displayFilepath.Text = _filePath;
           _TempFileLocation = _filePath;

        }

        //names the script manager which will be used when the user attempts to upload a form / gives an error if they incorrectly attempt to upload
        protected void UploadButton_Click(object sender, EventArgs e)
        {
            //if file is located
            if (FileUploadControl.HasFile)
            {
                try
                {
                    //allow content type of document / docx
                    if (FileUploadControl.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
                    {
                        //if the file is is less than 51mb
                        if (FileUploadControl.PostedFile.ContentLength < 10485760) // 10mb)
                        {
                            //name the filename, find the path of the name
                            string filename = Path.GetFileName(FileUploadControl.FileName);
                            //path of server upload (we just need to save it as a variable to be found on the next page, as it will be made / deleted
                            FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
                            //update the label with file uploaded
                            StatusLabel.Text = "Upload status: File uploaded!";

                            XMLextractor(Server.MapPath("~/") + filename);

                            //move onto template wizard page
                            //Response.Redirect("http://portal.acoura.com/admin/templatewizard.aspx", false);

                          WordprocessingDocument _TempDoc = WordprocessingDocument.Open(Server.MapPath("~/") + filename, true);

                         labelContentControls.Text = fileUpload_Displayx(GetContentControls(_TempDoc));

                            //will be used to grab the document string
                            //return;

                        }
                        else
                            //display the size the file needs to be less than
                            StatusLabel.Text = "Upload status: The file has to be less than 10mb!";
                    }
                    else
                        //tell the user only docx files are accepted
                        StatusLabel.Text = "Upload status: Only DOCX files are accepted!";
                }
                catch (Exception ex)
                {
                    //display the exception message, in which case it would be either size / type / if it's present
                    StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }


            }

        }
   // }

   //insert or link to XMLfromDocument file here. This will declare the variables
   //and take the required XML sections from the content controls of a document
   //needs to run as the file is uploaded, then return the control content titles

       // internal static class W
       //{

        //}


        public static XNamespace w =
            "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

        public static XName body = w + "body";
        public static XName sdt = w + "sdt";
        public static XName sdtPr = w + "sdtPr";
        public static XName tag = w + "tag";
        public static XName val = w + "val";
        public static XName sdtContent = w + "sdtContent";
        public static XName tbl = w + "tbl";
        public static XName tr = w + "tr";
        public static XName tc = w + "tc";
        public static XName p = w + "p";
        public static XName r = w + "r";
        public static XName t = w + "t";
        public static XName rPr = w + "rPr";
        public static XName highlight = w + "highlight";
        public static XName pPr = w + "pPr";
        public static XName color = w + "color";
        public static XName sz = w + "sz";
        public static XName szCs = w + "szCs";


        public static XDocument GetXDocument(this OpenXmlPart part)
        {
            XDocument xdoc = part.Annotation<XDocument>();
            if (xdoc != null)
                return xdoc;
            using (Stream str = part.GetStream())
            using (StreamReader streamReader = new StreamReader(str))
            using (XmlReader xr = XmlReader.Create(streamReader))
                xdoc = XDocument.Load(xr);
            part.AddAnnotation(xdoc);
            return xdoc;
        }

        public static XElement GetContentControls(WordprocessingDocument document)
        {

            XElement contentControls = new XElement("ContentControls",
                document
                    .MainDocumentPart
                    .GetXDocument()
                    .Root
                    .Element(W.body)
                    .Elements(W.sdt)
                    .Select(tableContentControl =>
                        new XElement("Table",
                            new XAttribute("Name", (string)tableContentControl
                                .Element(W.sdtPr).Element(W.tag).Attribute(
                                    W.val)),
                            tableContentControl
                                    .Descendants(W.sdt)
                                    .Select(fieldContentControl =>
                                            new XElement("Field",
                                                new XAttribute("Name",
                                                    (string)fieldContentControl
                                                          .Element(W.sdtPr)
                                                          .Element(W.tag)
                                                          .Attribute(W.val)
                                                    )
                                            )
                                    )
                        )
                    )
            );
            //display the content controls in a web form in this project using this, the control will have to be added to templatewizard
            return contentControls;

            //need to mark the source which will be a file in the same directory as this for test purposes.

        }
   //display the TemplateWizard boxes and button here, hide viewstate and display viewstate2  
   //display content controls from doc on box1, field names from DB in box2
   //just create a string here that represents the final state of data being taken from XMLfromDocument


      // public string fileUpload_Displayx (XElement _contentcontrol)
      // {
      //      string str= "";
       //     str= _contentcontrol.Name.ToString();

       //    return str;

     //  }

   //public static displayDatabase(object sender, EventArgs e)
  // {

   //}
   //run the validate button on templatewizard, will mark up any problems or give green light


   //if red, allow users to replace fields in the left column, from ones in the atabase on the right


   //display upload button when validation is succesful. When Upload button runs, Take to new 
   // / existing page of reports, allow users to download this 






</script>

<!-- The following section will include all the html and forms etc !-->

<!-- on implementation, create different divs for each section, and style appropriately.  !-->
<div>


<!--Testing View state form!-->
ViewState Data: <b><asp:Label ID="lblString" runat="server"/></b>
<asp:Button ID="btnClick" runat="server" Text="Get ViewState Data" OnClick="btnClick_Click"/>
<asp:Button ID="Closeform" runat="server" Text ="Hide PageState" OnClick="Close" />


<br /><br /><br /><br /><br />

<!-- User upload control !-->
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
<asp:TextBox Text="" runat="server" ID="displayFilepath" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />

 <br /> <br /> <br /> <br />



<!-- Viewdata2, the document and data from DB will be displayed !-->

<!-- Document data !-->
<div id="box1" class="box">

    <div class="box-top">
        Data Sources inside document
    </div>
    <div class="box-middle">
        <asp:Label runat="server" id="labelContentControls" text="label of content in document" />
        <p> Test </p>
        <p> Test </p>
    </div>
    <div class="box-bottom">
    </div>
</div>    

<!--Data from DB !-->
<div id="box2" class="box">

    <div class="box-top">
        Data sources existing on the server
    </div>
    <div class="box-middle">
        <asp:Label runat="server" id="labelDatabasefields" text="label of content in database" />
        <p> Test </p>
        <p> Test </p>
    </div>
    <div class="box-bottom">
    </div>
</div>


<input type="button" value="Create Template" id="view" class="form_button"/>



</div>

最佳答案

是的,这就是问题所在:

public static XDocument GetXDocument(this OpenXmlPart part)

这不是在顶级静态非泛型类中声明的,而扩展方法必须是。

我强烈建议您停止混合代码和 HTML - 将代码放在代码隐藏和其他类中。 GetXDocument 方法需要位于单独的类中,因为根据编译错误,它需要位于静态类中。

编辑:一个糟糕的选择是让它不是扩展方法:

public static XDocument GetXDocument(OpenXmlPart part)

然后你的电话看起来像这样:

document.MainDocumentPart
        .GetXDocument()

将需要:

GetXDocument(document.MainDocumentPart)

关于c# - 必须在非通用静态类中定义扩展方法 - 从文档中提取 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20680478/

有关c# - 必须在非通用静态类中定义扩展方法 - 从文档中提取 XML的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  9. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  10. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

随机推荐